Search code examples
loopsansibleinventory

How can I get a list of child groups in Ansible?


I have an inventory file that looks like this:

[master]
host01

[nl]
host02

[us]
host03

[satellites:children]
nl
us

How can I get a list of groups that have satellites as their parent?

I am looking for a solution that works similar to this:

- debug: msg="{{ item }}"
  with_items: "{{ groups['satellites:children'] }}"

Update:

The only solution I was able to come with is this:

- debug: {{ item }}
  with_items: "{{ groups }}"
  when: item != "master" and item != "satellites" and item != "all" and item != "ungrouped"

But that is not very flexible.


Solution

  • You can try the following approaches:

      vars:
        parent: 'satellites'
      tasks:
          # functional style
        - debug: msg="{{hostvars[item].group_names | select('ne', parent) | first}}"
          with_items: "{{groups[parent]}}"
          # set style
        - debug: msg="{{hostvars[item].group_names | difference(parent) | first}}"
          with_items: "{{groups[parent]}}"
    

    Also select('ne', parent) is interchangeable with reject('equalto', parent) depending on what is more readable to you.

    Links:
    set theory operator
    select and reject filters


    Updated answer based on comments. inspiration from this thread.

    vars:
        parent: 'satellites'
    tasks:
        - name: build a subgroups list
          set_fact: subgroups="{{ ((subgroups | default([])) + hostvars[item].group_names) | difference(parent) }}"
          with_items: "{{groups[parent]}}"
    
        - debug: var=subgroups
    

    output:

     "subgroups": [
            "nl",
            "us"
        ]