24

What's the sane way run a task only if the host belongs to one or more groups?

Currently, I'm using a boolean within the relevant group, e.g.:

Inventory file

[db_servers:vars]
copy_connection_string=true

Task

-
  name: Copy db connection string file
  synchronize: src= ... (truncated for clarity)
  when: copy_connection_string is defined

What's the right condition in the when clause to check whether the current host belongs to the db_servers group?

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • 2
    Possible duplicate of [Run task only if host does not belong to a group](https://stackoverflow.com/questions/21008083/run-task-only-if-host-does-not-belong-to-a-group) – lingfish Aug 23 '17 at 22:49
  • I wouldn't say so. That's a similar question but it's not the same question. – Jason Swett Mar 23 '20 at 19:39

1 Answers1

45

Run task when a host server is a member of a specific group

Ansible contains special or magic variables - one of the most common is group_names which is a list (array) of all the groups the current host is in.

- name: Copy db connection string file
  synchronize:.........
  when: "'db_servers' in group_names"

The above Ansible task will only run if the host is a member of the db_servers group.

notapatch
  • 6,569
  • 6
  • 41
  • 45
Arbab Nazar
  • 22,378
  • 10
  • 76
  • 82