home blog contact about
Making the Most of Ansible Variable Precedence

Making the Most of Ansible Variable Precedence

Ansible Variable Precedence

In order from lowest precedence to highest (IE: #2 overrides #1, #3 overrides #2 and so on):

1. command line values (for example, -u my_user, these are not variables)
2. role defaults (as defined in Role directory structure)
3. inventory file or script group vars
4. inventory group_vars/all
5. playbook group_vars/all
6. inventory group_vars/*
7. playbook group_vars/*
8. inventory file or script host vars
9. inventory host_vars/*
10. playbook host_vars/*
11. host facts / cached set_facts
12. play vars
13. play vars_prompt
14. play vars_files
15. role vars (as defined in Role directory structure)
16. block vars (only for tasks in block)
17. task vars (only for the task)
18. include_vars
19. set_facts / registered vars
20. role (and include_role) params
21. include params
22. extra vars (for example, -e "user=my_user")(always win precedence)

In order to understand the precence, we must first understand the ansible directory layout which informs the search path used to locate content like templates, inventories, and tasks.

(This repo can be used if you want to test git clone https://github.com/andir01d/ansible_sample_template.git)


├─ ansible.cfg
├─ inventories/
│  ├─ main.yml
├─ group_vars/
│  ├─ group1.yml       # here we assign variables to production groups
│  └─ group2.yml
├─ host_vars
│     ├─ hostname1.yml    # here we assign variables to individual production hosts
│     └─ hostname2.yml
└─ roles
   ├─ common/                # this hierarchy represents a "role"
   │  ├─ tasks/              #
   │  │  └─ main.yml         #  <-- tasks file can include smaller files if warranted
   │  ├─ handlers/           #  
   │  │  └─ main.yml         #  <-- handlers file
   │  ├─ templates/          #  <-- files for use with the template resource
   │  │  └─ ntp.conf.j2      #  <------- templates end in .j2  
   │  ├─ files/
   │  │  ├─ bar.txt          #  <-- files for use with the copy resource
   │  │  └─ foo.sh           #  <-- script files for use with the script resource  
   │  ├─ vars
   │  │  └─ main.yml         #  <-- variables associated with this role  
   │  └─ defaults
   │     └─ main.yml         #  <-- default lower priority variables associated with this role  
   └─ monitoring # same kind of structure as "common" was above, done for the webtier role

https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html#splitting-out-vars