Variable Precedence in Ansible

From bib. source

Ansible’s documentation provides the following ranking:

  1. --extra-vars passed in via the command line (these always win, no matter what).
  2. Task-level vars (in a task block).
  3. Block-level vars (for all tasks in a block).
  4. Role vars (e.g. [role]/vars/main.yml) and vars from include_vars module.
  5. Vars set via set_facts modules.
  6. Vars set via register in a task.
  7. Individual play-level vars: 1. vars_files 2. vars_prompt 3. vars
  8. Host facts.
  9. Playbook host_vars.
  10. Playbook group_vars.
  11. Inventory: 1. host_vars 2. group_vars 3. vars
  12. Role default vars (e.g. [role]/defaults/main.yml)

The above ranking is a ranking of variable precedence, wherein the top-most entry describes variables that override variable definitions as described in lower-most entries (Geerling 2023, 106-107).

There are different ways to approach variable definitions adjusted for this precedence, but there are some rules that can help clear any variable definition conflicts (Geerling 2023, 107):

  • “Roles […] should provide sane default variables.”
  • “Playbooks should rarely define variables,” but “rather should” include variable files.
  • Only truly host- or group-specific variables should be defined in host or group entries.”
  • “Dynamic and static inventory sources should contain a minimum of variables”
  • “Command line variables (-e) should be avoided when possible […].”

definition variable_files variable_file inventory_file playbook playbooks roles Ansible configuration_management configuration_file command_line command_lines command_line_interface command_line_interfaces ad-hoc_command ad-hoc_commands


bibliography

  • “Ansible Playbooks - Beyond the Basics.” In Ansible for DevOps: Server and Configuration Management for Humans, 2nd ed., 84–122. Leanpub, 2023.