Pcornel
Automation · Templates

Jinja2

Cheat sheet · https://pcornel.dk/topic.php?topic=5807

Back to the Topic

Answer

Jinja2 is the Python template engine used by Ansible, Salt, NetBox and Nornir, with {{ variables }}, {% if %} and {% for %} blocks, filters and macros.

Remember

  • Jinja2 uses {{ }} for values and {% %} for logic.
  • StrictUndefined fails on missing variables.
  • Whitespace control avoids blank lines.

First checks

  • python3 -c "from jinja2 import Environment,StrictUndefined;print(Environment(undefined=StrictUndefined).from_string('{{ x }}').render(x=1))" — render with strict undefined
  • ansible <host> -m debug -a "msg={{ inventory_hostname }}" — Ansible Jinja2
  • trim_blocks/lstrip_blocks — whitespace

Verify in this order

data + Jinja2 → rendered text

Where it usually breaks

Input/desired state → request accepted → job/task terminal status → target object read-back → effective runtime state → original workload → regression/rollback readiness.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=5807

Confirmation

Confirm action

Continue?