Ansible "AnsibleUndefinedVariable" in a template - Fix Jinja2 Vars
The template module rendered a Jinja2 file that references a variable the host does not have. Rendering fails because Ansible cannot resolve the name, so the file is never written.
What this error means
A template: task fails with AnsibleUndefinedVariable, naming the variable and the .j2 file. It is deterministic - the same inventory/vars leave the variable undefined every run, so the template never renders.
fatal: [web01]: FAILED! => {"msg": "AnsibleUndefinedVariable: 'app_port' is
undefined", "template": "templates/nginx.conf.j2"}Common causes
Variable not defined for this host
The template references {{ app_port }} but it was never set in inventory, group_vars/host_vars, role defaults, or --extra-vars for the host being templated.
Typo or wrong scope
A misspelled variable, or one defined for a different group/host than the one rendering, leaves Jinja2 unable to resolve it.
How to fix it
Provide a default in the template
Use a Jinja2 default so an optional variable does not break rendering, and define required ones explicitly.
# templates/nginx.conf.j2
listen {{ app_port | default(8080) }};Define the variable for the host
- Set
app_portin the correct group_vars/host_vars, role defaults, or pass--extra-vars. - Add an early
assertthat required variables are defined to fail with a clear message. - Run with
-vto confirm which variables the host actually has.
How to prevent it
- Give optional template variables a Jinja2
| default(...). - Declare required variables in role defaults and
assertthem early. - Keep variable names consistent between templates and var files.