Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible merges group_vars when deploying to same host in different groups

Tags:

ansible

Here's an example of the problem:

inventory file:

[group1] www.example1.com

[group2] www.example1.com

group_vars files:

group_vars/group1:
    a_var: aaa

group_vars/group2:
    a_var: bbb

If we run this playbook:

- name: ...
  hosts: group1
  roles:
    - ...

The variables from group_vars/group1 and group_vars/group2 overwrite each other if we're deploying to the same server.

Expected result: a_var=aaa

Actual result: a_vars=bbb

It seems like the vars get parsed and attached to the host rather than the staying with the group (so group_vars get merged even if you are not using that group and last group merged wins !!!!). is that a normal behavior ?

like image 464
Amine Benatmane Avatar asked Aug 31 '16 14:08

Amine Benatmane


2 Answers

As a workaround, you can choose a different name for each group and set the var ansible_host for each with true hostname/IP. Example:

[group1]
example1-group1 ansible_host=192.168.0.10

[group2]
example1-group2 ansible_host=192.168.0.10

In this case, Ansible considers that you have two different hosts, with dedicated hostvars and groupvars but reaches them the same way.

like image 145
mathmons Avatar answered Oct 11 '22 11:10

mathmons


is that a normal behavior ?

Yes, if host is in multiple groups, variables from only one group (the latter) will be honored.

From docs:

It is ok to put systems in more than one group, for instance a server could be both a webserver and a dbserver. If you do, note that variables will come from all of the groups they are a member of, and variable precedence is detailed in a later chapter.

like image 44
Konstantin Suvorov Avatar answered Oct 11 '22 11:10

Konstantin Suvorov