Search code examples
ansibleansible-inventory

How to check if inventory group exists in Ansible?


Is there a way to check if an inventory group exists (and if it doesn't, the task should be skipped)?

I know you can check if a host exists in a group by way of "'Cool-Server' in groups['WebServers']" but I am having a hard time figuring out how to make ansible ignore a task if the group itself is not defined.

I basically have a task like such:

- name: Some Task
  command: ls -ltr
  when:
    - "'Cool-Server' in groups['WebServers]"

and I'd like for ansible to be able to only run this task if the group WebServers itself is defined in the inventory, otherwise it should skip the task. Right now, if the group WebServers does not exist in the inventory, ansible/jinja freaks out and errors because its trying to look for something that does not exist.

Any ideas?


Solution

  • The following should work for you:

    when:
      - "'Cool-Server' in groups['WebServers] | default([])"