Ansible variables precedence
This topic I really don’t like. There are so many entities in priority list (places to put variables) that it’s impossible to remember. Moreover, it’s impossible to recognize.
Here is my puzzle for today. What has higher priority:
inventory.yaml
:
...
all:
vars:
foo: ['inventory']
Or group_vars/all.yaml
in the same directory as inventory?
---
foo: ['file']
First at all. What is ‘group_vars/all.yaml’? Naive answer is ‘its a group variables for group “all”’. Ha-ha, this is Ansible.
There are few group_vars out there. Don’t get confused, because it’s confusing.
Ansible have two ‘group_vars/all’.
- inventory group_vars/all
- playbook group_vars/all
(Yep, from here).
The logic says that ‘inventory group_vars/all’ is a group vars in the inventory, and ‘playbook group_vars/all’ is a groups vars in the directory with playbook.
But what if inventory and playbook are in the same directory? Whom belong the file group_vars/all.yaml
in this case?
The thing is that documentation says nothing about it. So, let’s do an experiment. I use Ansible 2.9.6.
A test run says:
ok: [localhost] => {
"foo": [
"file"
]
}
So, I conclude, that in situation when an inventory and a playbook both are in the same directory, group_vars/all
is belong to inventory.
But! And there is a big butt for you!
We have the same variable defined inside inventory file (group vars for ‘all’) and in inside the external group variables file for inventory for group all
.
Which one is winning? As our experiment shows, the external file wins. Retrospectively I can justify this (we load inventory file first with all variables, and then add variables from inventory group vars).
But this is super confusing. That’s why I avoid touching the topic of precedence for Ansible.
Moreover, I have terminology. Just see how clumsy it is: ‘inventory group variables for group all from external group_vars/all have precedence over inventory group variables for group all from inventory file’.
Can you even repeat this without error? I can’t. Variables is the most broken part of Ansible, and variable precedence is the most broken part of the broken part in the Ansible.