Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Conditions · Templates

Direct answer

Conditions in templates include or change output based on variables, such as {% if vlan_id %} ... {% endif %} in Jinja2, so one template covers several cases.

When to use this

Use this when templates include parts conditionally.

First 30 seconds

1. Conditions include/exclude blocks.

2. Keep conditions simple; compute in data.

3. Test true/false cases.

4. Use is defined checks carefully.

5. Comment intent.

Operational verification

condition → included block

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 templates include parts conditionally.
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

Verification needs a render matrix, not a single happy-path render. Exercise true, false, missing, null/empty and type-invalid values for each important branch and compare the complete rendered fragment with approved fixtures or semantic assertions. In Jinja, use an environment configuration that mirrors production, including undefined handling and enabled extensions, because the same template can behave differently under another environment. Then pass the rendered artifact through the target format/configuration validator where available. Finally, deploy or test the artifact in a safe context and read back the consumer-visible state. Store the context fixture, rendered output, validator result and target read-back as separate observations. This shows whether a failure comes from the condition, the render environment, generated syntax, or the downstream system rather than reducing all four to 'template failed'.

Step 2 Common mistakes Narrow the fault
  • Deep nested conditions.
Step 3 Where it fails Narrow the fault

Template condition failures have at least four boundaries: context construction, template expression evaluation, document rendering, and target parsing/application. An undefined key is an input-contract or render-environment problem; a false condition may be correct given the input; a malformed generated file is a rendering problem; and a valid generated file rejected by a service is a target-schema/version problem. Never fix the target by weakening undefined handling or adding broad defaults until the missing input contract is understood. Likewise, do not infer that a rendered branch was applied merely because it appears in a file—the target may ignore, override or normalize it. Preserve the template revision, engine version, context subset, rendered artifact hash and downstream validation/read-back. Remediate the earliest demonstrated boundary and re-run the exact fixture that originally exposed the issue.

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
  • {% if %} includes parts conditionally.
  • Test every branch.
  • Keep logic simple.
Key checks
  • {% if enable_ssh %}…{% endif %} — condition example
  • Test both branches — coverage
  • Avoid deep nesting — readability
ReferenceWhy it matters1 section · depth on demand

In depth

Template conditions include or exclude parts of the output based on data, with {% if %} blocks in Jinja2. They let one template serve several device roles or optional features.

{% if role == 'access' %}
spanning-tree portfast default
{% elif role == 'distribution' %}
spanning-tree vlan 1-4094 priority 4096
{% endif %}
{% if snmp is defined and snmp.v3_users %}
{% for u in snmp.v3_users %}
snmp-server user {{ u.name }} {{ u.group }} v3 auth sha {{ u.auth }} priv aes 128 {{ u.priv }}
{% endfor %}
{% endif %}

If conditions grow complex, split into role-specific templates or move decisions into the data model.

ReferenceImportant terms & boundaries1 section · depth on demand

Mechanics

Template conditions execute inside the template engine's expression model, not inside the language of the generated file. In Jinja, if/elif/else, tests such as is defined, comparisons, membership, boolean operators, filters and inline conditional expressions evaluate values from the render context. Truthiness and undefined-value behavior depend on the engine/environment, and attribute lookup can resolve through object attributes or mapping items according to Jinja rules. A condition can therefore render valid text while being semantically wrong because an expected key was absent, had a different type, or was coerced through truthiness. The condition also controls only which text is emitted, but it does not show that the emitted configuration is valid for the downstream parser or target service. Treat template evaluation and target configuration semantics as separate interpreters.

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

Keep conditional logic small enough that the template remains a presentation layer over an explicit data contract. Put policy-heavy decisions in validated input preparation where they can be unit-tested, and reserve template conditions for rendering choices that are naturally tied to output shape. Define expected input keys, types and defaults outside the template, choose deliberate undefined behavior (often strict in CI/validation), and avoid conditions that silently accept both strings and booleans for the same field. Store templates and their input schema/fixtures in the same reviewed repository so changes to a branch are evaluated with representative contexts. When a template targets multiple platform versions, prefer explicit feature/version selectors rather than probing for incidental fields. The lifecycle should include render validation before deployment and target validation after deployment; a clean render is only an intermediate artifact.

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 > Conditions. 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 → Conditions · operational reference

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

LayerTemplates → Conditions 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

The primary output of a template condition is the rendered document, plus any render exception; there is no useful standalone 'condition output' unless the template explicitly emits one. Compare output at the structural level where possible: parsed YAML/JSON/XML or normalized configuration is usually more reliable than whitespace-sensitive text diffing. Preserve enough context to explain why a branch rendered, but do not dump secret-bearing input objects into logs. Undefined-variable errors, type errors and syntax errors should be retained verbatim because they identify the template layer, while a syntactically valid rendered file belongs to the downstream validation layer. When whitespace control changes, distinguish formatting-only differences from semantic ones. A good diagnostic shows input fixture → branch expectation → rendered structural result → target interpretation so operators do not mistake a visually plausible file for a confirmed configuration.

Confirmation

Confirm action

Continue?