Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do ansible host_vars work?

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?

like image 713
mjallday Avatar asked Oct 29 '14 21:10

mjallday


People also ask

What are Ansible Host_vars?

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.

How group_ vars works in Ansible?

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.

How does Ansible dynamic inventory work?

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.

What is group vars and host vars in Ansible?

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.


1 Answers

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):

  1. Vars set on the command line -e foo=set_on_cmd_line
  2. Vars set in the vars_files: block in the play
  3. Vars set in the vars: block in the play
  4. Vars set in host_vars/
  5. Vars set in group_vars/
  6. Role default vars roles/.../defaults/main.yml

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.

like image 148
jarv Avatar answered Sep 26 '22 10:09

jarv