Variable Precedence in Ansible
From bib. source
Ansible’s documentation provides the following ranking:
--extra-varspassed in via the command line (these always win, no matter what).- Task-level vars (in a task block).
- Block-level vars (for all tasks in a block).
- Role vars (e.g.
[role]/vars/main.yml) and vars frominclude_varsmodule.- Vars set via
set_factsmodules.- Vars set via
registerin a task.- Individual play-level vars: 1.
vars_files2.vars_prompt3.vars- Host facts.
- Playbook
host_vars.- Playbook
group_vars.- Inventory: 1.
host_vars2.group_vars3.vars- 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.