Ansible: applying roles to certain groups in a single playbook

In a single Ansible playbook, you may wish to apply some roles to all hosts, while limiting other roles to only certain groups.

While it is certainly possible to apply a role to all hosts and then use a ‘when’ to filter down to the desired group like below:

- hosts: all
  gather_facts: yes
  roles: 
    - prerequisites-for-all
    - { role: echo, when: "'myrole' in group_names" }

This results in a lot of extra output where the “skipping” of each non-matching host task is shown.  Instead, it is much cleaner to use multiple ‘hosts’ section in a single playbook.

# applied to all hosts
- hosts: all
  gather_facts: yes
  roles: 
    - prerequsites-for-all

# only applied to 'myrole' group
- hosts: myrole
  roles: 
    - role: echo

You can find my playbook in git at playbook-for-role-group.yaml

REFERENCES

ansible, targeting hosts and groups