Reputation: 1261
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 ?
Upvotes: 8
Views: 4629
Reputation: 1441
Even though it is a feature it becomes really annoying when you are using a local ansible connection to manage remote resources like databases.
I managed to get around this by using a unique name in the hosts in the hosts file.
The following playbook (print.yml
) will print db1
and changing the hosts to group2
will print db2
---
- name: Manage DB
hosts: group1
tasks:
- debug:
msg: "{{ database.name }}"
Inventory folder:
dev
├── group_vars
│ ├── group1
│ │ └── all.yml
│ └── group2
│ └── all.yml
└── hosts
└── all.yml
group_vars/group1/all.yml:
database:
name: db1
group_vars/group2/all.yml:
database:
name: db2
and contents of hosts/all.yml:
(NOTE: the dbnode1
vs dbnode2
below)
all:
children:
group1:
hosts:
dbnode1:
ansible_connection: local
group2:
hosts:
dbnode2:
ansible_connection: local
ansible -i dev print.yml
Upvotes: 0
Reputation: 121
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.
Upvotes: 12
Reputation: 68269
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.
Upvotes: 1