'Avoid duplicate role execution

I have a playbook like

- hosts: hostA
  roles:
    - roleA
    - roleB

- hosts: hostB
  roles:
    - roleA
    - roleC

and an inventory

all:
  children:
    hostA:
      hosts:
        machine1
    hostB:
      hosts:
        machine2

So far, everything works fine. But now I have a second environment with inventory

all:
  children:
    hostA:
      hosts:
        machine3
    hostB:
      hosts:
        machine3

RoleA gets executed twice when I run the playbook. Is there a way to prevent that?



Solution 1:[1]

The most DRY, straightforwad and easy way to "fix" this is:


- name: run common roles for both groups
  hosts: hostA:hostB
  roles:
    - roleA

- name: run specific roles for group A
  hosts: hostA
  gather_facts: false
  roles:
    - roleB

- name: run specific roles for group B
  hosts: hostB
  gather_facts: false
  roles:
    - roleC

If you are unclear with the meaning of hosts: hostA:hostB in the first play, have a look at ansible hosts/group patterns

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1