Ansible Variables: Define, Use, and Override Variables (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
How to use Ansible variables in playbooks, inventory, roles, and command line. Variable types, precedence, register, set_fact, extra vars, vault encryption with examples.
Ansible Variables: Define, Use, and Override Variables (Complete Guide)
Variables are the backbone of flexible Ansible playbooks. Define them in inventory, playbooks, roles, files, or the command line — then reference them anywhere with {{ variable_name }}.
Define Variables
In a Playbook
In Variable Files
In Inventory
In Group/Host Vars Directories
From Command Line (Extra Vars)
Extra vars (-e) have the highest precedence — they override everything.
Register Variables
Capture task output for use in later tasks.
Common Register Fields
set_fact — Runtime Variables
Variable Precedence (Low → High) Command line values (-u, etc.) Role defaults (roles/x/defaults/main.yml) Inventory file group vars Inventory group_vars/all Inventory group_vars/ Inventory file host vars Inventory host_vars/ Host facts / registered vars Play vars: Play vars_prompt: Play vars_files: Role vars (roles/x/vars/main.yml) Block vars Task vars include_vars set_fact / registered vars Role params include params Extra vars (-e) ← highest
Variable Data Types
Access Variables
Variable Filters
Encrypted Variables (Vault)
FAQ
How do I define variables in Ansible?
Define variables in playbook vars: section, vars_files:, inventory files, group_vars/ and host_vars/ directories, role defaults/vars, or via -e on the command line. Each location has different precedence.
What is Ansible variable precedence?
Ansible has 22 levels of variable precedence. Extra vars (-e) have the highest. Role defaults have the lowest. The most common override order: role defaults < inventory < playbook vars < set_fact < extra vars.
How do I use registered variables in Ansible?
Use register: varname on a task to capture its output. Access fields like varname.stdout, varname.rc, varname.changed. Use in conditionals: when: varname.rc == 0.
What is the difference between vars and set_fact?
vars are defined at play/task level and scoped to that context. set_fact creates variables at runtime that persist for the host across plays. set_fact can use values from previous tasks.
How do I set a default value for a variable?
Use the default filter: {{ my_var | default('fallback_value') }}. Use default(omit) to skip an optional module parameter when the variable is undefined.
Conclusion
Variables make Ansible playbooks flexible and reusable. Understand the precedence order, use group_vars and host_vars for inventory-specific values, and encrypt sensitive data with Vault.
Related Articles • Ansible Variable Precedence: Complete Order • Ansible set_fact: Create Runtime Variables • Ansible Vault: Encrypt Sensitive Data • Ansible Extra Vars: Override Variables from CLI
Category: troubleshooting