Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active March 19, 2023 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barbietunnie/a21a38a157f6323aef41edbcd89f20fd to your computer and use it in GitHub Desktop.
Save barbietunnie/a21a38a157f6323aef41edbcd89f20fd to your computer and use it in GitHub Desktop.
Ansible Variable Precedence

Ansible Variable Precedence

Here is the order of precedence from least to greatest (the last listed variables override all other variables):

  1. command line values (for example, -u my_user, these are not variables)
  2. role defaults (defined in role/defaults/main.yml) [1]
  3. inventory file or script group vars [2]
  4. inventory group_vars/all [3]
  5. playbook group_vars/all [3]
  6. inventory group_vars/* [3]
  7. playbook group_vars/* [3]
  8. inventory file or script host vars [2]
  9. inventory host_vars/* [3]
  10. playbook host_vars/* [3]
  11. host facts / cached set_facts [4]
  12. play vars
  13. play vars_prompt
  14. play vars_files
  15. role vars (defined in role/vars/main.yml)
  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 general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope. Variables in the defaults folder inside a role are easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in the namespace. Host and/or inventory variables override role defaults, but explicit includes such as the vars directory or an include_vars task override inventory variables.

Ansible merges different variables set in inventory so that more specific settings override more generic settings. For example, ansible_ssh_user specified as a group_var is overridden by ansible_user specified as a host_var.

[1] Variables defined in inventory file or provided by dynamic inventory.

[2] Includes vars added by ‘vars plugins’ as well as host_vars and group_vars which are added by the default vars plugin shipped with Ansible.

[3] When created with set_facts’s cacheable option, variables have the high precedence in the play, but are the same as a host facts precedence when they come from the cache.

[4] Within any section, redefining a var overrides the previous instance. If multiple groups have the same variable, the last one loaded wins. If you define a variable twice in a play’s vars: section, the second one wins.

Source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment