128

I'd like to able to run an ansible task only if the host of the current playbook does not belong to a certain group. In semi pseudo code:

- name: my command
  command: echo stuff
  when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}"

How should I do this?

rgrinberg
  • 9,638
  • 7
  • 27
  • 44

3 Answers3

248

Here's another way to do this:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html :

group_names is a list (array) of all the groups the current host is in.

Rubinum
  • 547
  • 3
  • 18
Iskandar Najmuddin
  • 2,736
  • 1
  • 15
  • 9
  • 4
    +1 and if you don't include the surrounding quote you get the error: `This one looks easy to fix. It seems that there is a value started with a quote, and the YAML parser is expecting to see the line ended with the same kind of quote.` – Peter Ajtai Aug 12 '15 at 21:56
  • 5
    I find this approach more readable and convenient to write, but both work equally well. `when: inventory_hostname not in groups.certain_groups` – Liam Feb 16 '17 at 08:20
  • 5
    This way is more robust than `inventory_hostname in groups['groupname']` because in cases where the grout itself does not exist, Ansible will throw an error like "Make sure your variable name does not contain invalid characters like '-': argument of type 'StrictUndefined' is not iterable" – hamx0r Mar 17 '17 at 19:05
  • 2
    The link now should be https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables. The doc has been moved around. – lexotero Mar 15 '21 at 17:22
  • I dont understand if `` then why would someone put a `if my current host not in my current groups execute command` which will never execute in their tasks? – YosSaL Dec 11 '22 at 10:09
26

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var
mdur
  • 244
  • 2
  • 9
nvartolomei
  • 1,505
  • 12
  • 15
3

I have came up with this:

- name: my command
  command: echo stuff
  when: inventory_hostname not in groups.get('your-group', [])

YosSaL
  • 667
  • 6
  • 15