Tyler Durden
Tyler Durden

Reputation: 55

Run a tasks only for hosts that belong to a certain group

I'm trying to skip a task in a playbook based on the group in my inventory file.

Inventory:

[test]
testserver1

[qa]
qaserver1

[prod]
prodserver1
prodserver2

I'm pretty sure I need to add the when clause to my task, but not sure how to reference the inventory file.

- name: Add AD group to local admin
  ansible.windows.win_group_membership:
    name: Administrators
    members:
      - "{{ local_admin_ad_group }}"
    state: present
  when: inventory is not prod

Basically, I want run the task above on all the servers except for the ones in the group called prod.

Upvotes: 0

Views: 147

Answers (1)

toydarian
toydarian

Reputation: 4574

You can have all your hosts in one environment, but I suggest to use different environment files for dev, staging, qa and prod. If you separate it by condition, it can happen quite fast, that you mess up some condition or forget to add it to a new task altogether and accidentally run a task on a prod host, that should not run there.

If you still want to have all your hosts in the same inventory, you can either separate them using different plays (you can have multiple in the same playbook) and then using hosts to specify where they should run.
For example:

- name: play one
  hosts:
    - qa
    - test
  tasks:
    <all your tasks for qa and test>

- name: play two
  hosts: prod
  tasks:
    <all your tasks for prod>

If you want to do it on a per-task level, you can use the group_names variable.
For example:

- name: Add AD group to local admin
  ansible.windows.win_group_membership:
    name: Administrators
    members:
      - "{{ local_admin_ad_group }}"
    state: present
  when: '"prod" not in group_names'

In that case you need to be really careful if you change things, so your conditions are still the way they are supposed to be.

Upvotes: 1

Related Questions