6

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?

trikelef
  • 518
  • 1
  • 7
  • 26
  • could you show your ansible playbook? – c4f4t0r May 06 '19 at 12:06
  • This [reading](https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) might help, especially the note at the end of the chapter. – Zeitounator May 07 '19 at 17:32
  • Just add a custom name for host and bind to ip using ansible_host. The response is here. https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#hosts-and-non-standard-ports – Mihai R Jun 06 '19 at 08:32
  • @MihaiR Thanks. This could be a solution, although not so elegant. – trikelef Jun 06 '19 at 10:50

1 Answers1

7

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 }}"
TheDESTROS
  • 385
  • 3
  • 10
  • That works, but is much error-prone. I'd recommend to use a random and unique hostname, combined with `ansible_ssh_host`, pointing to the real server. ``` [db_gmbh_prod] db_gmbh_prod_ ansible_ssh_host=1.2.3.4 ansible_ssh_user=root ``` – pansen Dec 01 '22 at 13:46