Ansible - Using a logical OR to match host groups

Tony-Caffe picture Tony-Caffe · Aug 31, 2017 · Viewed 9.6k times · Source

I am trying to get this to only apply to my dev and hydra servers. I have 2 host files with hosts in them. The dev-all host group is [dev-all:children] dev-group1 dev-group2

The hydra group only contains one server but is in a different host file. When I run ansible I use a command like such for hydra group ansible-playbook -i environments/hydra site.yml and for dev groups I use this command ansible-playbook -i environments/dev site.yml.

My question is, how do I get this when condition to apply only to hydra when I call hydra or only to dev-all when I call dev? This would help me avoid adding this group to prod servers in another host file. The dev-all group contains many dev server groups in the dev file and I am basically trying to include all of them from the host file so I made the dev-all:children group to grab them all.

I cant seem to get them to match the when OR condition. Perhaps there is a better way to write the when statement.

- name: add dev environment sudo user group group: name=dev_sudo state=present gid=8002 tags: - groups - sudo-group when: (inventory_hostname in groups["dev-all"]) or (inventory_hostname in groups['hydra'])

Answer

Konstantin Suvorov picture Konstantin Suvorov · Sep 1, 2017

You can use group_names which is a list (array) of all the groups the current host is in. See magic variables.

Like:

when: ('dev-all' in group_names) or ('hydra' in group_names)

or:

when: ['dev-all', 'hydra'] | intersect(group_names) | count > 0