jost84
jost84

Reputation: 11

Ansible loop through nested inventory lists

I'm trying to loop through a nested ansible inventory looks like this:

    inventory:
      group_one:
        - name: 'entry-one-a'
          description: 'one-a'
          group_two:
            - name: 'entry-two-aa'
              description: 'two-aa'
              group_three:
                - name: 'entry-three-aaa'
                  description: 'three-aaa'
                - name: 'entry-three-aab'
                  description: 'three-aab'

I've tried it with the following loop, but without success:

  - name: print vars
    ansible.builtin.debug:
      msg: '{{ item }}'
    loop: '{{ inventory.group_one.group_two|subelements("group_three") }}'

Any good idea how to loop through the inventory?

Upvotes: 1

Views: 275

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67984

Iterate the third loop in the included task, e.g.

shell> cat group_three.yml
- debug:
    msg: "{{ item.0.name }} {{ item.1.name }} {{ item2.name }}"
  loop: "{{ item.1.group_three }}"
  loop_control:
    loop_var: item2
    - include_tasks: group_three.yml
      with_subelements:
        - "{{ inventory.group_one }}"
        - group_two

gives

  msg: entry-one-a entry-two-aa entry-three-aaa
  msg: entry-one-a entry-two-aa entry-three-aab

Upvotes: 1

Related Questions