Nested looping in ansible (loop inside loop)

From Notes_Wiki
Revision as of 10:34, 21 March 2015 by Saurabh (talk | contribs)

<yambe:breadcrumb>Ansible_tips_and_tricks|Ansible tips and tricks</yambe:breadcrumb>

Nested looping in ansible (loop inside loop)

For nested looping in ansible at least two lists are required. Then for each item of first list, one item from second list can be obtained. Thus if two lists have m and n values. Then total m*n operations can be performed. For nested looping use 'with_nested' similar to shown below:

---
- name: Demo of with_nested
  hosts: all
  remote_user: root

  vars:
    list1: [1, 2, 3]
    list2: [a, b, c, d]

  tasks:
    - name: Printing message
      debug: msg="Values are {{item[0]}} and {{item[1]}}"
      with_nested:
        - list1
        - list2

Learned from ansible-examples github repo at https://github.com/ansible/ansible-examples/blob/master/language_features/loop_nested.yml