Run ansible task on multiple inventory host groups
Asked Answered
B

3

5

I am looking to run the same task on multiple inventory groups, for eg:

[big_group]
greenhat
localhost
redhat
linux

[small_group]
localhost

[redhat_group]
redhat

From my playbook I need to run a task on both small_group and redhat_group

My task is as below

  - name: Disable HTTPS service from firewalld
    firewalld:
      service: https
      permanent: false
      state: disabled
      zone: public
      immediate: true
    when: inventory_hostname in groups['small_group']
    when: inventory_hostname in groups['redhat_group']

Received a warning as

 [WARNING]: While constructing a mapping from firewall.yml, line 6, column 5, found a duplicate dict key (when). Using last defined value only.

Playbook result :

TASK [Disable HTTPS service from firewalld] **************************************************************************************************************************************************
skipping: [localhost]
skipping: [redhat]

How can I specify multiple groups in when: inventory_hostname in groups[]

Bonheur answered 11/5, 2020 at 5:43 Comment(0)
D
9

You cannot have several when clause in a task. In your case, you just have to join the two groups (+) and remove the multiple entries if any ( with the unique filter, for future inventory changes).

when: inventory_hostname in ((groups['small_group'] + groups['redhat_group']) | unique )

Meanwhile, there is a much more convenient way IMO using the inventory_hostnames lookup and taking advantage of patterns as you do in a normal play

when: inventory_hostname in lookup('inventory_hostnames', 'small_group:redhat_group')
Downstage answered 11/5, 2020 at 6:38 Comment(0)
J
0

This is very old, but I was able to get this working with the the two clauses in ( ) and an "or" condition

when: 
  - (inventory_hostname in groups["small_group"] or inventory_hostname in groups["redhat_group"] ) 
Jacobi answered 29/9, 2023 at 17:49 Comment(0)
L
-1

Basically it is doable with a list:

when:
  - ansible_hostname in groups['small_group']
  - ansible_hostname in groups['redhat_group']

But the way with using lookup is more 'pro'.

Lowry answered 2/3, 2022 at 17:41 Comment(1)
This does not answer the question as the task will run only for hosts which belong to both groups.Downstage

© 2022 - 2024 — McMap. All rights reserved.