How to set a task to run for a specific inventory group?

Solution 1:

In order to use group membership in a conditional for a task, play or block, you would use the format:

when: inventory_hostname in groups["<group name>"]

Specifically to your initial question:

when: inventory_hostname in groups["appservers"]

To reach all machines under north, you would simply change it to: when: inventory_hostname in groups["north"]

In regards to your follow up clarification (specifying a group in a particular "location"), as group names must be unique in ansible, there's no need to distinguish which appservers group you're referring to, as appservers can only ever be in one location.

If you attempt to create two appservers groups, only the first one would actually be parsed by the ansible engine; any subsequent group of the same name will be ignored. So, if you were planning to (in the future) have an appservers group under north and an appservers group under south, you'll find that only members in the first group will be included.

In ansible, how we achieve this (my assumption of what you may want in the future), the ansible way to proceed is to add the hosts to multiple groups like so, and adjust your limit or conditional appropriately:

all:
  children:
    north:
      hosts:
        a.domain.com:
        b.domain.com:
    south:
      hosts:
        y.domain.com:
        z.domain.com:
    appservers:
      hosts:
        a.domain.com:
        y.domain.com:
    dbservers:
      hosts:
        b.domain.com:
        z.domain.com:

In this example, if you wanted all app servers, you would just target appservers. If you wanted only appservers in the north region, then you would set your limit on the play to north:&appservers, or alternatively use the conditional

when:
  - inventory_hostname in groups["appservers"]
  - inventory_hostname in groups["north"]

In any event, I think you might need a refresher in how inventory is structured in ansible, for that I would recommend the user guide; there are also some great resources on various training sites that can go into much greater detail.

For further information about more complex targeting using multiple groups (combinations, unions, and exclusions, etc), I suggest you review this other user guide.


On a personal note, initially I thought the setup was tedious and limited, but as I have become more familiar with using it, I actually find it more dynamic than the alternative.