30
votes

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?

1

1 Answers

38
votes

Since the documentation is not very specific on this topic here is the order of precedence for vars in the current version of Ansible:

  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

Here you can see thee order of precedence from least to greatest (the last listed variables winning prioritization) in the ansible docs.

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.