Search code examples
ansibleansible-2.xansible-inventoryansible-factsansible-template

Ansible get hostnames from one group as a variable to another play


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.,


Solution

  • 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].