Explicitly empty groups in Ansible

I have a playbook that is applied to various inventories. Some of the plays do not apply to all inventories.

I can leave the group out of an inventory, or I can add it but leave it empty. In both cases, this yields a warning when the optional play is run:

[WARNING]: Could not match supplied host pattern, ignoring: myoptionalgroup

I still want to use this class of warning to generate a report to catch mistakes - e.g. where a group name has been mistyped in the play or inventory, but I do not want it to appear when I know it is deliberate.

How can I best suppress the warning in those situations where I know that there will be no hosts to which a play applies in a given inventory?


Hardly there is a way to suppress this warning itself, but you can forcefully end play on some condition.

For example, you can check hosts in current play run and end play if there's a dummy host:

---
- hosts: localhost
  gather_facts: no
  tasks:
    - debug:
        msg: hello 1

- hosts: optional
  gather_facts: no
  pre_tasks:
    - meta: end_play
      when: ('dummy' in play_hosts)
  tasks:
    - debug:
        msg: hello 2

- hosts: localhost
  gather_facts: no
  tasks:
    - debug:
        msg: hello 3

This will:

  • give a warning if optional group does not exist or is empty and skip play
  • end play with pre-task if optional group contains dummy host
  • execute tasks as usual if optional group contains other hosts and there's no dummy