2

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?

  • could you show your ansible playbook? – c4f4t0r May 6 '19 at 12:06
  • This reading might help, especially the note at the end of the chapter. – Zeitounator May 7 '19 at 17:32
  • Just add a custom name for host and bind to ip using ansible_host. The response is here. docs.ansible.com/ansible/latest/user_guide/… – Mihai R Jun 6 '19 at 8:32
  • @MihaiR Thanks. This could be a solution, although not so elegant. – trikelef Jun 6 '19 at 10:50
3

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 }}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.