Ansible - Loop through nested list using the with_nested parameter
by
Jeremy Canfield |
Updated: July 06 2023
| Ansible articles
The following parameters can be used to loop through each item in a list.
- loop
- vars
- with_items
- with_indexed_items
- with_list
- with_nested (this article)
- with_sequence
The with_nested parameter can be used to loop over two unique lists. In this example, the debug module and the with_nested parameter are used.
---
- hosts: all
remote_user: root
tasks:
- debug:
msg: "{{ item[0] }} and {{ item[1] }}"
with_nested:
- [ 'apple', 'banana' ]
- [ 'onion', 'pepper' ]
Which should produce the following.
TASK [debug]
ok: [server1.example.com] => (item=['apple', 'onion']) => {
"msg": "apple and onion"
}
ok: [server1.example.com] => (item=['apple', 'pepper']) => {
"msg": "apple and pepper"
}
ok: [server1.example.com] => (item=['banana', 'onion']) => {
"msg": "banana and onion"
}
ok: [server1.example.com] => (item=['banana', 'pepper']) => {
"msg": "banana and pepper"
}
Here is a bit of a more practical example.
- name: append foo and bar to file1.txt and file2.txt
lineinfile:
path: "{{ item[0] }}"
line: "{{ item[1] }}"
with_nested:
- [ 'file1.txt', 'file2.txt' ]
- [ 'foo', 'bar' ]
Did you find this article helpful?
If so, consider buying me a coffee over at