Ansible - Using a logical OR to match host groups
Asked Answered
A

1

8

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'])

Aulos answered 31/8, 2017 at 21:23 Comment(0)
S
17

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
Scyphozoan answered 1/9, 2017 at 6:37 Comment(5)
That worked! Thank you! Is there a way to apply it to a whole task file instead of a specific instance? Like having a main.yml, hydra.yml, dev-web1.yml etc. That way you dont have to do a When Conditional like the above for everything in that file?Aulos
Make separate yml files and use include + when inside main.yml.Scyphozoan
Can you give an example please? I understand the include is placed in the main.yml but how would I get the when condition for all items in the included yml file?Aulos
Just apply when statement to include as to any other module (like you did for group in OP)Scyphozoan
First option worked for me, second didn't - complained about syntaxCelka

© 2022 - 2024 — McMap. All rights reserved.