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 satellites have their parent?

I am looking for a solution that works something like this:

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

Update:

The only solution I was able to contact was:

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

But it is not very flexible.

+5
source share
1 answer

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) , whichever is more readable to you. Strike>

References:
set theory operator
select and reject filters


Updated response based on comments. inspiration from this topic .

 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" ] 
+2
source

All Articles