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.
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.
You can use the option --list-hosts. It will show all the host IPs from your inventory file.
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', '.
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 .
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"
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With