Playbook inventory group targeting

I’ve harped on about this before. It’s what I call “fully articulated” inventory groups. In our shop, we group things by service line, and within that by environment (dev, tst, prd, …). We also prepend our work group’s initials to all our host group names to keep them from colliding with those of other work groups. We’re called the “Middleware” group, hence the leading “mw_”. So all our host group names look like this:

mw_<service>[_<env>[_<hostclass>[_<subclass>]]]

Whenever we need it, we’ll also define a literal “all” group at any of those placeholder levels. Then we can say:

 when: inventory_hostname in groups['mw_xkcd_all_head']

Or the equivalent for your inventory if it were “fully articulated”:

when: inventory_hostname in groups['all_masters']

That lets us avoid contortions in our when: clauses like the following – which works, but who wants to read it, much less write it.:

---
# /home/utoddl/ansible/zeitler/test.yml
- name: Play group name games
  hosts: all
  gather_facts: false
  tasks:
    - name: Are we in a *_master group
      ansible.builtin.debug:
        msg:
         - 'group_names: {{ group_names }}'
         - '{{ inventory_hostname }} is in a *_master group.'
      when: group_names | map("regex_search", "_master") | reject("==", None) | length

which produces

TASK [Are we in a *_master group] ***********************************************************
task path: /home/utoddl/ansible/zeitler/test.yml:7
ok: [master1ofb] => 
  msg:
  - 'group_names: [''b'', ''b_masters'']'
  - master1ofb is in a *_master group.
skipping: [slave1ofb] => 
  false_condition: group_names | map("regex_search", "_master") | reject("==", None) | length
skipping: [slave1ofa] => 
  false_condition: group_names | map("regex_search", "_master") | reject("==", None) | length
ok: [master1ofa] => 
  msg:
  - 'group_names: [''a'', ''a_masters'']'
  - master1ofa is in a *_master group.

I’m going to quote myself in case someone didn’t follow the link above, because I think it’s worth repeating.

1 Like