I have some tasks that should only be processed if the host (inventory_hostname) is the first in the group of servers it’s defined in.
For example, here is my hosts file. Note that the group names are not fixed - the Role I want to use them in cannot rely on the name of the groups - it needs to be a bit more dynamic than that:
I have a playbook which I call like so, by passing in the name of the two groups - again - the name of these groups could vary, or I could add a 3rd or 4th group in.
Yes, there is a “groups” variable which is a dictionary with group name keys where the values are a list of hosts in that group. That is, groups[dev_cluster] = [“server1”, “server2”, “server3”]. So you can do a inventory_hostname == groups[dev_cluster][0] comparison for the first item.
Note: I have not tested this in playbooks, only templates, and you might run into bugs if your group has zero hosts. You also need to consider the scenario where a host is in more than one group.
That is close, but that still needs the name “dev_cluster” in the cpmparison function.
I am more looking for something that determines if the inventory_hostname is the first server in either of the groups specified in the play.
The groups may change across environments, so the task needs to be dynamic in its evaluation.
Is there any way to pick up the “hosts” that were specified by the play?