Skip to content
Latchkey

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.

ansible output
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.

nginx.conf.j2
# templates/nginx.conf.j2
listen {{ app_port | default(8080) }};

Define the variable for the host

  1. Set app_port in the correct group_vars/host_vars, role defaults, or pass --extra-vars.
  2. Add an early assert that required variables are defined to fail with a clear message.
  3. Run with -v to 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 assert them early.
  • Keep variable names consistent between templates and var files.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →