Bootstrap FreeKB - Ansible - Loop through nested list using the with_nested parameter
Ansible - Loop through nested list using the with_nested parameter

Updated:   |  Ansible articles

The following parameters can be used to loop through each item in a list.

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 Buy Me A Coffee



Comments


Add a Comment


Please enter 85a133 in the box below so that we can be sure you are a human.