Ansible - with_nested loop parameter

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' ]

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |