how to get the current executing host group_name not group_names in ansible?

5k views Asked by At

I have read How do you get group name of the executing role in ansible
I also read https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html
but I can't understand it.

If the same host IP in different host_groups, I think: "ansible is separated execute when executing the host, it should belong to only one group_name, not group_names".
How can I get current executing host gorup_name, not group_names?

2

There are 2 answers

2
Matthew Liu On

First,

you can write one host in several groups.

Second,

In my opinion, Getting the 'group_name' of executing host make no sense

Whatever you using ad-hoc(playbook), you must declare which group of hosts you want to execute command(role), all group must be written in your ansible command(role) even if you want to execute on all hosts.

So when the command(role) are running, you have already know which group is running now.

Third,

Even if you run command(role) on two groups which have the same hosts, why do you want to know the host is from which group.

UPDATE:

1.Like my origin reply, you can define many groups include the same host.

For instance, this is the inventory file

[production]
machine01
machine02
[staging]
mchines01

And Using this judging condition in tasks.

when:
  - inventory_hostname in groups['production']

2.And you also can add tags for the specific tasks.

For instance

- name: set hostname
  hostname:
    name: machine03
  tags:
    - production
    - staging

- name: reboot
  reboot:
    reboot_timeout: 1200
  tags:
    - staging

Running ansible-playbook commond with -t option

-t TAGS, --tags=TAGS  only run plays and tasks tagged with these values
1
jconnell On

It sounds like you want want the group equivalent to inventory_hostname. Unfortunately, it doesn't exist. You might consider setting an extra variable during execution as a workaround. Example: --extra-vars targetgroup=group1

This would work well if you typically only target one group. If targeting multiple groups, consider creating a new parent group for each combination and then targeting that.