I created a repo to reproduce my scenario.
Essentially we are loading an inventory with our hosts, we can override values per-host via the inventory without issue but would like to try and utilize host_vars.
I'm not 100% clear on how host vars are matched to the host. I read the ansible repo for examples but cannot seem to get it to work as documented so I'm looking for some scrutiny of our setup.
When I run the command ansible-playbook -i ansible.inventory site.yml -clocal
in my example repo I expect the host_vars/{{ ansible_hostname }}
file to be read and override anything set in the vars but that does not appear to be happening.
Can someone please point me at a working example so I can see where we are going wrong?
The host_vars is a similar folder to group_vars in the repository structure. It contains data models that apply to individual hosts/devices in the hosts. ini file. Hence, there is a YAML file created per device containing specific information about that device.
It uses hosts file and group_vars directory to set variables for host groups and deploying Ansible plays/tasks against each host/group. Files under group_var directory are named after the host group's name or all, accordingly, the variables will be assigned to that host group or all the hosts.
In Ansible, Dynamic inventory is generated either by scripts which are written in a programming language like python, php etc. or using available inventory plugins. When using script, they gets all real time data from the target source environments, like Cloud platforms AWS, OpenStack, GCP etc.
Group variables are a convenient way to apply variables to multiple hosts at once. Before executing, however, Ansible always flattens variables, including inventory variables, to the host level. If a host is a member of multiple groups, Ansible reads variable values from all of those groups.
Since the documentation is not very specific on this topic here is the order of precedence for vars in the current version of Ansible (the first item has the highest precedence):
See Ansible docs for a more detailed list.
You should think of host_vars and group_vars more like defaults rather than overrides for defaults. If you have the same var set in you vars_files: block like you do in your example it will take precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With