Opt-out from Web Archive
April 29, 2024
Loops and nested loops with Ansible
In my opinion, one of the less understandable constructs in Ansible concerns loop management. If we then talk about nested loops, the situation becomes even more complex. In this short post, we’ll see the recipes for:
- looping over a list;
- looping over a dictionary;
- nested loops.
Looping Over a List
The simplest loop involves using a list and performing a series of actions on each element, by default item
:
- ansible.builtin.debug:
msg: "Now reading {{ item }}"
with_items: "{{ list1 }}"
As we can see, within the loop, the element is accessible through the variable item
.
Looping Over a Dictionary
If we’re looping (it wouldn’t be the correct term) over a dictionary, we’ll likely need to access both the key and the value. The syntax is similar to the previous case:
- ansible.builtin.debug:
msg: "Now reading {{ item.key }} by {{ item.value }}"
with_dict: "{{ dict1 }}"
In this case, we see that the key is accessible through item.key
while the associated value is accessible through item.value
.
Nested Loops
If we need to use nested loops, the syntax becomes more complex, and we’ll need to rely on external files. Let’s see the syntax:
- ansible.builtin.include_tasks: sub_task1.yml
with_items: "{{ list1 }}"
loop_control:
loop_var: outer_item
For each element in the list list1
, the playbook will execute the tasks contained in the file sub_task1.yml
. In the execution of the subtasks, the current element is accessible through the variable outer_item
:
- ansible.builtin.debug:
msg: "Now reading {{ outer_item }} from outer loop"
In the same file, we can perform another loop by calling a third file:
- ansible.builtin.include_tasks: sub_task2.yml
with_items: "{{ list2 }}"
loop_control:
loop_var: inner_item
The file sub_task2.yml
defines the tasks that will use the variables from the first (outer) and second (inner) loop:
- ansible.builtin.debug:
msg: "Now reading {{ outer_item}} / {{ inner_item }} from inner loop"