I haven't been able to find the syntax for loop + zip when combining more than 2 lists.
Since Ansible 2.5, as shown here, the following syntax replaces with_together with loop + zip:
- name: with_together
debug:
msg: "{{ item.0 }} - {{ item.1 }}"
with_together:
- "{{ list_one }}"
- "{{ list_two }}"
- name: with_together -> loop
debug:
msg: "{{ item.0 }} - {{ item.1 }}"
loop: "{{ list_one|zip(list_two)|list }}"
My question is, whereas when using with_together, you could simply append lists, and reference them with iterating numbers, I haven't been able to find the method to use with loop + zip. I have tried:
loop: "{{ list_one|zip(list_two)|zip(list_three)|zip(list_four)list }}"
Without success.
Ansible's syntax also supports the idea of nested looping. Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task.
item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .
Ansible offers the loop , with_<lookup> , and until keywords to execute a task multiple times.
The loop keyword executes the same task multiple times. It stores the value of each item in a variable called item . So, instead of specifying the names of the users to be added, simply specify a variable called item enclosed between double curly braces as shown below.
You can append additional arrays inside the zip filter itself.
zip(list, list, list, ...)
For example:
- hosts: localhost
become: false
gather_facts: false
tasks:
- vars:
list_one:
- one
- two
list_two:
- three
- four
list_three:
- five
- six
debug:
msg: "{{ item.0 }} {{ item.1 }} {{ item.2 }}"
loop: "{{ list_one | zip(list_two, list_three) | list }}"
When run:
PLAY [localhost] *********************************************************************************************************************************************
TASK [debug] *************************************************************************************************************************************************
ok: [localhost] => (item=['one', 'three', 'five']) => {
"msg": "one three five"
}
ok: [localhost] => (item=['two', 'four', 'six']) => {
"msg": "two four six"
}
PLAY RECAP ***************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With