Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Konstantin Kelemen Avatar asked Sep 23 '16 07:09

Konstantin Kelemen


People also ask

How do I list groups in Ansible inventory?

If you just want a list of the groups within a given inventory file you can use the magic variables as mentioned in a couple of the other answers. In this case you can use the groups magic variable and specifically just show the keys() in this hash (keys + values). The keys are all the names of the groups.

How can I get a list of hosts from an Ansible inventory file?

You can use the option --list-hosts. It will show all the host IPs from your inventory file.

Where is Group_vars in Ansible?

In this, group_vars directory is under Ansible base directory, which is by default /etc/ansible/. The files under group_vars can have extensions including '. yaml', '. yml', '.

What is Inventory_hostname Ansible?

The inventory_hostname is the hostname of the current host, as known by Ansible. If you have defined an alias for a host, this is the alias name. For example, if your inventory contains a line like this: server1 ansible_host=192.168.4.10. then inventory_hostname would be server1 .


1 Answers

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"
    ]
like image 199
stacksonstacks Avatar answered Oct 16 '22 06:10

stacksonstacks