3

Here is inventory file.

[abc]
host1
host2

[123]
host3

And main.yml

#play1
- hosts: abc
  roles:
    - { role: abc }
  tasks: 
    ...
#play2
- hosts: 123
  roles:
    - { role: 123 }
  tasks:
    debug: msg="{{inventory_hostname}}"

Basically I need to run some commands in host3 and the commands need host1 and host2 in it. So how can I get host1 and host2 which are in group abc into play2 debug: msg="{{inventory_hostname}}", I know inventory_hostname is getting host3. is there any other way I can get only host1 and host2. Let me know if I'm not clear.

Thanks in Advance.,

venkatama
  • 55
  • 1
  • 7

2 Answers2

3

You can use the "groups" magic variable as discussed in the documentation.

groups is a list of all the groups (and hosts) in the inventory. This can be used to enumerate all hosts within a group.

So you can reference, e.g., groups['abc'] or groups['abc'][0].

thinkmassive
  • 758
  • 6
  • 15
chash
  • 3,975
  • 13
  • 29
  • Thank you, they worked. I also looped "groups" magic variable and working like charm – venkatama Jun 12 '20 at 17:58
  • Is there a way I can use OR operation in groups magic variable like `with_items: {{ groups['123'] }} or {{ groups['234'] }}` – venkatama Jun 12 '20 at 18:07
  • What is your intent? Do you want to combine both groups, or use `groups['234']` if there are no hosts in `groups['123']`? – chash Jun 12 '20 at 18:15
  • so there are 2 environments and the script creates hosts file with what ever env the server falls in, like env1 is group['123']and env2 group['234']. they can be group [123] or [234] in the host file and when Im looping hosts from the whatever group exists in host file ```. - debug: msg: "{{item}}" with_items: "{{ groups['123'] }} or {{ groups['234'] }}"``` – venkatama Jun 12 '20 at 18:39
  • There's nothing really special about the groups variable. Treat it like any other variable. For instance, you could do `{{ groups['123'] | default(groups['234']) }}`. – chash Jun 12 '20 at 18:56
1

This is the one line solution:

- name: Print hostnames of 'registry' inventory group
  vars:
    registry_hostnames: "{{ groups['registry'] | map('extract', hostvars) | map(attribute='ansible_host') }}"
  debug:
    var: registry_hostnames

It uses the inventory names listed in groups variable to access the hostvars variable (with the inventory names as indices). From the resulting list we can use another map to access the inventory variable that we're interested in.

jwhb
  • 516
  • 4
  • 19