Pcornel
Automation · Ansible

Jinja2

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

Back to the Topic

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

BoundaryHealthy evidenceSuspicious evidence
Inputs / selectionCorrect inventory, hosts, variables/facts and content are explicitWrong scope, stale facts, hidden precedence or content-version drift
ExecutionConnection, privilege, module/task context and ordering match intentUnreachable, wrong execution host, privilege/plugin failure or misleading skip/change state
Result semanticsPer-host/item results are preserved and interpreted correctlyAggregate recap hides partial/skipped/handled failures
Target proofResource/workload read-back and rerun confirm convergenceGreen 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

Confirmation

Confirm action

Continue?