AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,100 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example" published by Apress, and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

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 ArticlesAnsible Variables: Complete GuideAnsible Facts GuideAnsible Playbook Guide

Category: troubleshooting

Browse all Ansible tutorials · AnsiblePilot Home