Ansible group_vars variable precedence (group_vars override other group_vars)
Solution 1:
This question is a bit old but the mentioned issue already exists, so I wrote my answer to one who needs the answer.
Actually, based on the documentation, Ansible focused on the Host and Task, so groups don’t really survive outside of inventory and host matching. To solve this problem, we need to add a prefix to variables of groups (like using namespacing to avoid conflicts).
# inventory/hosts.yml
webservers:
hosts:
host1:
host2:
vars:
webserver_my_var: ...
hostmaster:
hosts:
host1:
vars:
hostmaster_my_var: ...
And in the playbook, you can use the variable safely.
# playbooks/main.yml
- hosts: webserver
tasks:
- debug: var=webserver_my_var | mandatory
- hosts: hostmaster
tasks:
- debug: var=hostmaster_my_var | mandatory
This way you will eliminate the problem safely.
Using the same variable name inside multiple groups has another problem. It's hard to guess the value of a variable by just looking at the inventory, you need to know the relation between groups and the order/precedence of one group to another and it is hard work and error-prone.
Solution 2:
This is expected behaviour. See documentation:
Within any section, redefining a var will overwrite the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the 2nd one wins.