Fix Ansible "undefined variable" Error: Variable Scope and Precedence
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
How to fix Ansible undefined variable error. Understand variable scope, precedence, default values, and common causes. Complete troubleshooting guide.
Fix Ansible "undefined variable" Error: Variable Scope and Precedence
The "undefined variable" error is one of the most common Ansible issues. It means a variable is referenced but hasn't been defined in the current scope.
Common Causes
1. Variable Not Defined
2. Typo in Variable Name
3. Variable from Another Host
4. Conditional Variable
Best Practices to Prevent Undefined Variables
FAQ
Why does Ansible say my variable is undefined?
The variable hasn't been defined in the current scope — it may be missing from vars, inventory, var files, or not passed via -e. Check spelling, scope (host vs play), and variable precedence.
How do I set a default value for undefined variables?
Use the default Jinja2 filter: {{ my_var | default('fallback') }}. This returns 'fallback' if my_var is not defined.
How do I check if a variable is defined?
Use when: my_var is defined in conditionals, or {{ my_var | default(omit) }} to skip optional parameters entirely.
Related Articles • Ansible Variables: Complete Guide • Ansible Facts Guide • Ansible Playbook Guide
Category: troubleshooting