Ansible same host on different groups with group_vars

I have an Ansible inventory like the following:

[group1]
host1.mydomain

[maingroup:children]
group1

[group2]
host1.mydomain

I need to declare the same host on different groups since in this host there are two similar services collocated. In order to distinguish between the two services, I have created the following group vars:

group_vars/maingroup
---
servicepath: /service1/path

group_vars/group2
---
servicepath: /service2/path

When I first run a playbook with hosts: maingroup, then the same playbook with hosts: group2, it used the correct servicepath variable value each time (first run=/service1/path, second run=/service2/path).

However, in all subsequent retries when I run a playbook with maingroup I got the value servicepath: /service2/path

I only managed to run the playbook with correct variables with --extra-vars=@group_vars/group2 ansible-playbook parameter.

Could this be an Ansible bug or am I missing something?


Solution 1:

The fact is that ansible binds the value of variables to the host, not to the group. That is, there can be only one value for one variable on one host.

Try this just to override the value of the variable on the host everytime:

---
- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "{{ hosts }}"
  vars_files:
    - group_vars/{{ hosts }}.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

where {{ hosts }} = "maingroup" or "group2"

Example:

---
- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "group2"
  vars_files:
    - group_vars/group2.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"

- hosts: "maingroup"
  vars_files:
    - group_vars/maingroup.yml
  tasks:
  - name: my command
    command: "command with {{ servicepath }}"