Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Variables · Templates

Direct answer

Template variables are the values inserted into templates, coming from inventory, a source of truth or files. Missing or wrongly typed variables are the most common template bug.

When to use this

Use this when supplying variables to templates.

First 30 seconds

1. Template variables come from inventory, facts, defaults.

2. Use clear names.

3. default() filter for optional values.

4. Don't hide missing required data.

5. Document variables.

Operational verification

variables → template placeholders

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
Jinja 3.1/current
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformJinja 3.1/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when supplying variables to templates.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification path Verify boundary

Start by validating the input contract: expected key exists, type is correct, and any default/normalization has been applied intentionally. Render with the exact engine/environment configuration used in production and include fixtures for missing, empty, nested, list/map and special-character values. Inspect the parsed/normalized generated artifact rather than only the raw text, especially for YAML/JSON where quoting can change types. For a variable passed into a target application, perform a target-facing read-back to show that the value was interpreted as intended. When a variable comes from inventory, secrets or an API, record its source identifier/version without logging secret content. The verification chain should let an operator answer three separate questions: what value/type entered the renderer, what text/structure was emitted, and what state the consumer finally observed.

Step 2 Common mistakes Narrow the fault
  • Undefined variables rendering empty.
Step 3 Where it fails Narrow the fault

Separate variable-source, render-context, template-scope and target-interpretation boundaries. A value can be correct in inventory but replaced by a higher-precedence context value; available in an outer context but shadowed inside a loop or macro; represented as the wrong type during rendering; or emitted correctly yet parsed differently by the target language. Undefined behavior is another explicit boundary: strict failure and silent empty rendering have different operational consequences. Do not repair these problems by globally injecting more variables or weakening escaping. Show the selected source and precedence, inspect the value/type at render time, inspect generated structure, and finally verify the consumer state. That sequence keeps template variable troubleshooting deterministic and prevents a downstream configuration defect from being misdiagnosed as 'Jinja lost my variable'.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points
  • Variables come from inventory or a source of truth.
  • Types matter.
  • Missing variables cause most bugs.
Key checks
  • ansible-inventory --host <host> | jq . — variables available
  • Variable naming conventions — clarity
  • Defaults via | default() — missing values
ReferenceWhy it matters1 section · depth on demand

In depth

Template variables insert data into the rendered output, using {{ variable }} in Jinja2. Filters transform values (| upper, | default, | ipaddr), and undefined variables should cause an error rather than empty output.

hostname {{ inventory_hostname | upper }}
snmp-server location {{ site.name | default('unknown') }}
interface Vlan{{ mgmt.vlan }}
 ip address {{ mgmt.ip | ansible.utils.ipaddr('address') }} {{ mgmt.ip | ansible.utils.ipaddr('netmask') }}
from jinja2 import Environment, StrictUndefined, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'), undefined=StrictUndefined, trim_blocks=True, lstrip_blocks=True)
ReferenceImportant terms & boundaries1 section · depth on demand

Mechanics

Template variables are values supplied by the render context plus values created through engine features such as assignments, loop variables, macros and imports. In Jinja, a dotted expression can traverse attributes or mapping items and undefined values are represented by an Undefined implementation whose behavior is configurable. Variables are not Bash-like mutable process state: scope is shaped by template blocks, loops, macros, namespaces and imports, and assignments inside some scopes do not leak outward. Filters and tests can transform or classify values during rendering, while autoescaping and the target output format determine whether the emitted text is safe or correctly quoted. The same visual value can therefore have different meaning depending on whether it began as a number, boolean, list, secret, undefined value or preformatted fragment. Automation should preserve the distinction between source data type and rendered text.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
ReferenceConfiguration & state1 section · depth on demand

Lifecycle

Treat the render context as an API. Define names, types, required/optional status, defaults, units, secret classification and ownership outside the template, and version that contract with the template. Avoid scattering {% set %} assignments that recreate business logic inside presentation files; compute derived values before rendering or in small, well-tested macros/filters. Select a deliberate undefined policy and keep it consistent between CI and production. For secrets, render only where the destination requires the value, prevent debug dumps of the context, and ensure generated files receive appropriate permissions. When renaming variables, support a bounded compatibility window or fail clearly rather than silently falling back to an unrelated default. Keep fixture contexts for major variants so refactors can be regression-tested without contacting production systems.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docJinja 3.1/current 3.1/current

Authoritative/upstream documentation reviewed for bounded claims in Templates > Variables. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://jinja.palletsprojects.com/en/stable/templates/ · confidence 94%
Embedded reference data

Quick lookup tables

Templates → Variables · operational reference

Context-specific ownership, verification, output and failure-boundary lookup for Templates → Variables.

LayerTemplates → Variables operational reference
Context identityJinja 3.1/current + exact revision/input/target identity
Persistent intentVersioned contract/configuration with explicit ownership and prerequisites
VerificationValidate inputs/read current state → exercise bounded operation → independent target read-back
Output contractPreserve structured status/IDs/properties before human formatting
Failure boundarySeparate source/input/engine/controller execution from downstream target outcome
Depth when you need it

Deep reference

Healthy vs suspicious evidence

Output interpretation

Rendered variables always become part of an output artifact, but that does not mean string comparison alone is sufficient. A boolean rendered as "false" may be a string in one target and a boolean in another; an empty list may collapse into blank text; whitespace or escaping can alter a command/configuration token; and an undefined object can render silently depending on environment settings. Prefer structural parsers and normalized diffs for generated data formats. For troubleshooting, log variable names, source classes, types and safe summaries rather than full context dumps. If the template engine raises UndefinedError or a filter/type exception, preserve that error as render-layer evidence. If rendering succeeds, keep the artifact hash plus a small semantic excerpt and continue to the target validator/read-back instead of treating 'template produced text' as successful automation.

Confirmation

Confirm action

Continue?