Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible with_items if item is defined

Tags:

ansible

People also ask

What is use of With_items in Ansible?

What is Ansible with_items? The Ansible with_items is a handy plugin to perform loop operations in a playbook. The plugin accepts items and then passes them to the calling module. For example, you can pass a list of packages to install and then give each item in the list to the install task.

How do you define an item in Ansible?

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. the task will be run twice: first time with the variable item set to first , the second time with second .

What is Loop_var in Ansible?

Defining inner and outer variable names with loop_var However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control .


with_items: "{{ symlinks | default([]) }}"

The reason for this behavior is conditions work differently inside loops. If a loop was defined the condition is evaluated for every item while iterating over the items. But the loop itself requires a valid list.

This is also mentioned in the docs:

Note that when combining when with with_items (see Loops), be aware that the when statement is processed separately for each item. This is by design:

tasks:
  - command: echo {{ item }}
    with_items: [ 0, 2, 4, 6, 8, 10 ]
    when: item > 5

I think this is a bad design choice and for this functionality they better should have introduced something like with_when.

As you have already figured out yourself, you can default to an empty list.

with_items: "{{ symlinks  | default([]) }}"

Finally if the list is dynamically loaded from a var, say x, use:

with_items: "{{ symlinks[x|default('')] | default([])}}" 

This will default to an empty list when 'x' is undefined

Accordingly, fall back to an empty dict with default({}):

# service_facts skips, then dict2items fails?
with_dict: "{{ ansible_facts.services|default({})|dict2items|selectattr('key', 'match', '[^@]+@.+\\.service')|list|items2dict }}"