Ansible - using with_items and when conditional to
Solution 1:
You do not need to register your result with the item
salt. When you register the result of a loop (e.g. with_items
) the registered value will contain a key results
which holds a list of all results of the loop. (See docs)
Instead of looping over your original device list, you can loop over the registered results of the first task then:
- name: Check if the disk is partitioned and also ignore sda
stat: path=/dev/{{item}}1
with_items: disk_var
when: item != 'sda'
register: device_stat
- name: Create GPT partition table
command: /sbin/parted -s /dev/{{ item.item }} mklabel gpt
with_items: "{{ device_stat.results }}"
when:
- not item | skipped
- item.stat.exists == false
The condition not item | skipped
takes care of that elements which have been filtered in the original loop (sda) will not be processed.
While that might be a solution to your problem, your question is very interesting. There seems to be no eval
feature in Jinja2. While you can concatenate strings you can not use that string as a variable name to get to its value...
Solution 2:
Your tasks can be as simple as this...
- stat:
path: /dev/{{item}}1
with_items: ansible_devices.keys()
when: item != 'sda'
register: stats
- command: /sbin/parted -s /dev/{{item.item}} mklabel gpt
with_items: stats.results
when: item.stat | default(false) and item.stat.exists