Introduction Ansible template failures occur when Jinja2 templates reference variables that are not defined in the current scope. This causes task failures during configuration file generation.

Symptoms - "AnsibleUndefinedVariable: 'xxx' is undefined" - "template error: 'xxx' is undefined" - Template task fails with no clear indication of which variable is missing - Works in development but fails in production (different variable sets)

Common Causes - Variable not defined in inventory, vars, or group_vars - Variable name typo in template - Variable defined in wrong scope (host_vars vs group_vars) - Conditional variable access without default value - Loop variable used outside loop

Step-by-Step Fix 1. **Find the undefined variable**: ```bash ansible-playbook site.yml -vvv 2>&1 | grep -i "undefined" ```

  1. 1.Use Jinja2 default filter:
  2. 2.```jinja2
  3. 3.server_name {{ nginx_server_name | default('localhost') }};
  4. 4.max_body_size {{ nginx_max_body_size | default('1m') }};
  5. 5.`
  6. 6.Check variable availability:
  7. 7.```bash
  8. 8.ansible <host> -m debug -a "var=hostvars[inventory_hostname]"
  9. 9.`

Prevention - Use default() filter for optional variables - Define all variables in group_vars or host_vars files - Use ansible-lint to catch undefined variables - Test templates with --check mode before deployment - Document required variables for each role