Run task only if host does not belong to a group

Ansible

Ansible Problem Overview


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?

Ansible Solutions


Solution 1 - Ansible

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.

Solution 2 - Ansible

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrgrinbergView Question on Stackoverflow
Solution 1 - AnsibleIskandar NajmuddinView Answer on Stackoverflow
Solution 2 - AnsiblenvartolomeiView Answer on Stackoverflow