Ansible: how to skip a specific host or group in a playbook

If you search the Ansible documentation, you’ll probably end up using a when in your playbooks to skip a host.

I found out that it makes more sense to me to skip hosts from the hosts declaration, by prepending them with a !:

---
- name: check on which hosts this would run
  remote_user: root
  hosts: all !bastion
  tasks:
  - name: say hello
    debug:
      msg: "hello {{ ansible_hostname }}"

My hosts file looks like:

[common]
bh[01:02]
ws[01:20]
db[01:03]

[bastion]
bh[01:02]

[ws]
ws[01:20]

[db]
db[01:03]

Running the playbook with the usual commandline:

ansible-playbook -i hosts playbook.yaml

produces the expected result: the debug module is only run on webservers (ws) and databases (db), not on the bastion hosts (bastion).

I hope this will help some other sysadmin out there :)

Advertisements