Automation · Ansible
Jinja2
Cheat sheet · https://pcornel.dk/topic.php?topic=5406
Answer
Jinja2 is the expression and templating layer Ansible uses to resolve variables, filters, tests and control structures in many fields before modules receive final arguments.
Remember
- Expression parses ≠ value semantically correct; type coercion and defaults can hide bad inputs.
- Undefined handled by default ≠ missing data harmless; fallback can mask source errors.
- Rendered string ≠ original data type always; consumer expectations matter.
- Jinja2 logic ≠ task conditional scope automatically; templating and task controls have distinct contexts.
First checks
ansible localhost -m debug -a "msg={{ 'a,b' | split(',') }}"— test expression- Filters from collections (ansible.utils.ipaddr) — requirements
- StrictUndefined behaviour (error on undefined) — safety
Verify in this order
expression → Jinja2 → value
Where it usually breaks
A successfully rendered expression proves Jinja2 produced a value; it does not prove the value is correct for the receiving module or target application.
Jinja2 Ansible boundary map
| Boundary | Healthy evidence | Suspicious evidence |
|---|---|---|
| Inputs / selection | Correct inventory, hosts, variables/facts and content are explicit | Wrong scope, stale facts, hidden precedence or content-version drift |
| Execution | Connection, privilege, module/task context and ordering match intent | Unreachable, wrong execution host, privilege/plugin failure or misleading skip/change state |
| Result semantics | Per-host/item results are preserved and interpreted correctly | Aggregate recap hides partial/skipped/handled failures |
| Target proof | Resource/workload read-back and rerun confirm convergence | Green Ansible status treated as end-to-end acceptance |
Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=5406