Reputation: 2157
I have the following ansible setup:
ansible_test/playbooks/roles/main/main.yml
- name: hello world
hosts: all
tasks:
- name: hello!
shell: echo "test"
- name: display config
debug:
msg: "testvar is {{ hostvars['localhost']['testvar'] }}"
ansible_test/playbooks/inventory/hosts
[main]
localhost
[main:vars]
testvar=99
ansible-test/playbooks/inventory/group_vars/all/main.yml
testvar: 77
Now, when I modify the hosts file to the following:
[main]
localhost testvar=88
[main:vars]
testvar=99
I get an output of "testvar is 88". However, when I remove this, I get "testvar is 77" instead of the expected "testvar is 99".
When I add "testvar: 101" to a file: ansible_test/playbooks/inventory/host_vars/localhost.yml
, I get an output of "testvar is 101".
I am running the command:
/usr/bin/ansible-playbook -i playbooks/inventory/hosts playbooks/roles/main/main.yml --connection=local -vvvv
Why is this? Shouldn't this host-group definition still take precedence over group_vars?
Upvotes: 3
Views: 895
Reputation: 39294
Looks to me like your example makes all the sense based on the documentation about variable precedence:
Ansible does apply variable precedence, and you might have a use for it. Here is the order of precedence from least to greatest (the last listed variables override all other variables):
- command line values (for example,
-u my_user
, these are not variables)- role defaults (defined in role/defaults/main.yml) 1
- inventory file or script group vars 2
- inventory group_vars/all 3
- playbook group_vars/all 3
- inventory group_vars/* 3
- playbook group_vars/* 3
- inventory file or script host vars 2
- inventory host_vars/* 3
- playbook host_vars/* 3
- host facts / cached set_facts 4
- play vars
- play vars_prompt
- play vars_files
- role vars (defined in role/vars/main.yml)
- block vars (only for tasks in block)
- task vars (only for the task)
- include_vars
- set_facts / registered vars
- role (and include_role) params
- include params
- extra vars (for example,
-e "user=my_user"
)(always win precedence)
Where you can see that:
So in you first trial, you have
99
77
88
So, 88
wins.
Then you remove 88
99
77
So, 77
wins.
And then you add one:
99
77
101
So 101
wins.
Upvotes: 4