Migration

Strict Conditionals and Native Types: Migrating to the ansible-core 2.19 Templating Rules

The templating overhaul that landed in ansible-core 2.19 introduced three rules that still apply on 2.22: conditionals must evaluate to a real boolean, template delimiters are rejected inside expressions, and Jinja's native types survive templating instead of being re-parsed as Python literals. This guide reproduces each rule on localhost, shows the exact errors they raise, and gives you the migration edits that work on both old and new releases.

Version scope and prerequisites

The examples below target ansible-core 2.22.0, released 2026-11-02. The three rules described here were introduced in the 2.19 porting guide and still apply on 2.22; that is a statement about these rules, not a claim that nothing else in the templating engine changed across the releases in between, since minor releases carry fixes and refinements of their own. ansible-core 2.22 requires a controller Python of 3.13 to 3.15 and supports target Python 3.9 to 3.15. If you are still on 2.18 or earlier, this article describes the behaviour you will meet when you upgrade to 2.19 or later.

You need a throwaway directory and a controller Python 3.13 to 3.15. After the setup below, the playbooks run entirely against localhost over the local connection, create no application files, and make no network requests. They are not meant for the playground on this site, which runs ansible-core 2.22.0 but always runs with --check and screens inputs; run them in your own virtual environment.

Common setup

Create the project and pin the exact release:

mkdir -p ~/tma-templating && cd ~/tma-templating
python3.13 -m venv .venv
.venv/bin/python -m pip install 'ansible-core==2.22.0'
.venv/bin/ansible --version

Expected result: the version banner reports ansible [core 2.22.0] and a python version line pointing at the interpreter inside .venv. If pip refuses the install with a Requires-Python error, your python3.13 is older than the release needs — check which interpreter you actually used before changing anything else.

Add a config file and an inventory with a single local host:

[defaults]
interpreter_python = auto_silent
[local]
localhost ansible_connection=local

Rule one: a conditional must produce a boolean

Python and Jinja both accept "truthy" values anywhere a boolean is expected. A non-empty string, a non-empty dictionary, and the number 7 are all true. Upstream's position is that this convenience often masked serious logic errors that earlier releases could not reliably detect, so since 2.19 the engine inspects the type of a conditional result and raises an error when it is not a boolean.

One recognisable version of this bug is a flag that reaches the play as a string rather than a boolean. A YAML value written as "false" is a five-character string, and so is anything supplied as -e flag=false on the command line, because key=value extra-vars are parsed as strings. A group_vars file does not force this — an unquoted false there is a real boolean — so the thing to check is the quoting and the source, not the file. Either way, every non-empty string is truthy, so the old behaviour ran the task you meant to disable.

---
- name: Minimal broken conditional (this play is expected to fail)
  hosts: local
  gather_facts: false

  vars:
    feature_enabled: "false"

  tasks:
    - name: Use a string where a boolean is required
      ansible.builtin.debug:
        msg: The feature is on.
      when: feature_enabled
.venv/bin/ansible-playbook -i hosts.ini broken-conditional.yml

Expected result — the play fails on the first task with a typed error that points at the variable's origin:

TASK [Use a string where a boolean is required] *****
[ERROR]: Task failed: A 'when' expression failed: Conditional result (True) was
derived from value of type 'str' at 'broken-conditional.yml:7:22'.
Conditionals must have a boolean result.

Broken conditionals can be temporarily allowed with the
`ALLOW_BROKEN_CONDITIONALS` configuration option.

Note what the error tells you: the result was True, the type was str, and the value came from line 7 of the playbook. That provenance is the useful part of the 2.19 error handling work — you are told where the offending value was defined, not just where it was used.

The error message advertises ALLOW_BROKEN_CONDITIONALS. Treat that setting as an escape hatch for a migration window, not as a fix: it downgrades the error to a warning and leaves the logic bug in place, and the task in the example above still runs when you meant it to be skipped. The fix is to convert explicitly.

- name: Convert a string flag explicitly before using it as a condition
  ansible.builtin.set_fact:
    feature_enabled: "{{ feature_enabled_string | bool }}"

The same shape of fix covers the other broken-conditional patterns the upstream porting guide collects. When the expression is a bare variable, add a predicate that returns a boolean — | length > 0, is truthy, is defined, or an explicit comparison. When half the expression is accidentally quoted, as in that: name is defined and 'name | length > 0', the quoted half becomes the result; delete the quotes. When a YAML list item contains an unquoted key: value pair, the parser hands Ansible a dictionary rather than a string and you get Conditional expressions must be strings; quote the whole assertion. And when an operator binds more loosely than you expected — is contains "local" ~ "host" concatenates after the test, producing the string Truehost — add parentheses.

Rule two: no template delimiters inside an expression

when, that, changed_when, failed_when and until are already expressions. Writing {{ ... }} inside them asked the old engine to render a template and then evaluate the rendered string as a second pass of expression code. That multi-pass behaviour is exactly how untrusted data ended up being executed as a template, so it is gone.

---
- name: Minimal broken expression (this play is expected to fail)
  hosts: local
  gather_facts: false

  vars:
    replica_count: 3

  tasks:
    - name: Wrap a variable in template delimiters inside an expression
      ansible.builtin.assert:
        that:
          - "{{ replica_count }} > 1"

Expected result:

[ERROR]: Task failed: Syntax error in expression. Template delimiters are not
supported in expressions: expected token ':', got '}'

The fix is to delete the braces: replica_count > 1. Two related patterns deserve naming. Building an expression dynamically — that: inventory_hostname {{ comparison }} 'localhost' with comparison: == — used to work because task-argument templating rendered the string before assert parsed it. That is no longer supported, and upstream describes it as insecure rather than merely deprecated; restructure the play so the comparison is written out. Second, inside a module argument, {{ ... }} is still correct and required: the rule is about expression fields, not about every string in a playbook.

Rule three: trust is now explicit

Before 2.19, every string was treated as a potential template and strings coming from untrusted places — module results, remote facts — were wrapped in an "unsafe" marker that the template engine skipped. Any code that manipulated strings had to propagate that wrapper correctly, and upstream's own account of the change is that the long tail of places that failed to do so produced a series of CVE-worthy remote-code-execution vulnerabilities.

The model is now inverted. Only strings loaded from a trusted source are eligible to be rendered as templates. Playbooks, roles, variable files, and the built-in inventory plugins all yield trusted strings, so ordinary content keeps working. Untrusted values can still be referenced by a template; what they cannot do is be a template. A failure to propagate trust now costs you a template that silently renders as literal text, which is annoying, rather than a privilege escalation, which is not.

The silence is the part that bites during a migration: by default an untrusted template renders to its original string with no message. If a value is arriving on the far side as literal {{ something }}, set _ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR to warning or error for one run to find out where trust was lost. Upstream labels that variable experimental and subject to change, so use it as a diagnostic rather than wiring it into CI.

Rule four: native types, and the end of the literal-eval pass

Older releases ran templating in Jinja's string mode by default and then tried literal_eval on the result, falling back to the original string when that failed. A template that produced ['prod1', 'prod2'] as text therefore came back as a list by accident. Native Jinja mode is now used exclusively, the configuration option that selected the mode is deprecated and has no effect, and the final literal-evaluation pass is gone, so a template that produces a string stays a string.

Two concrete consequences. First, filters that only operate on strings no longer have their mistakes papered over: ['test1', 'test2'] | replace('test', 'prod') stringifies the list and returns "['prod1', 'prod2']". Use map('replace', 'test', 'prod') to apply the filter per element. Second, range() now always returns a range object, which cannot be stored as a variable or returned from a template; add | list when you want a list. An expression that evaluates to nothing in an {% if %} block can now produce the value None rather than an empty string, so write an explicit {% else %}{{ "" }} branch when you need a string. That edit is backward compatible with older releases.

The full local reproduction

This play exercises every rule above and passes. Save it next to ansible.cfg and hosts.ini.

---
- name: Strict conditionals and native types on ansible-core 2.22
  hosts: local
  gather_facts: false

  vars:
    feature_enabled_string: "false"
    feature_enabled_bool: false
    replica_count: 3
    tags_raw: ["web-1", "web-2"]

  tasks:
    - name: Report the controller version in use
      ansible.builtin.debug:
        msg: "ansible-core {{ ansible_version.full }} on {{ ansible_playbook_python }}"

    - name: The YAML string "false" is not the boolean false
      ansible.builtin.assert:
        that:
          - feature_enabled_string is string
          - feature_enabled_bool is boolean
          - feature_enabled_string != feature_enabled_bool
        success_msg: A quoted "false" stays a string; only the unquoted form is a boolean.

    - name: Convert a string flag explicitly before using it as a condition
      ansible.builtin.set_fact:
        feature_enabled: "{{ feature_enabled_string | bool }}"

    - name: The converted flag is a real boolean and is false
      ansible.builtin.assert:
        that:
          - feature_enabled is boolean
          - feature_enabled is false

    - name: This task is skipped because the converted flag is false
      ansible.builtin.debug:
        msg: You will not see this message.
      when: feature_enabled

    - name: Conditions reference variables directly, with no template delimiters
      ansible.builtin.assert:
        that:
          - replica_count > 1
          - inventory_hostname | length > 0
          - inventory_hostname is contains("local" ~ "host")

    - name: map keeps a list a list instead of stringifying it
      ansible.builtin.set_fact:
        tags_renamed: "{{ tags_raw | map('replace', 'web', 'app') | list }}"

    - name: Native types survive templating
      ansible.builtin.assert:
        that:
          - tags_renamed is sequence
          - tags_renamed is not string
          - tags_renamed == ["app-1", "app-2"]

    - name: A range has to be converted before it leaves the expression
      ansible.builtin.set_fact:
        indexes: "{{ range(0, replica_count) | list }}"

    - name: The converted range is a plain list
      ansible.builtin.assert:
        that:
          - indexes == [0, 1, 2]
.venv/bin/ansible-playbook -i hosts.ini templating-demo.yml --syntax-check
.venv/bin/ansible-playbook -i hosts.ini templating-demo.yml

Expected result: nine tasks report ok, the flag-gated debug task reports skipping, and the recap reads ok=9 changed=0 unreachable=0 failed=0 skipped=1. The first task prints the core version and the controller interpreter path, which is worth keeping in your own diagnostic plays — see interpreter diagnostics for why those two values are not the same thing.

If an assertion fails, do not diagnose it from the failure alone — several of these checks can also pass on older releases, so a failure does not establish which engine you are on. Gather three facts instead. Confirm the version with .venv/bin/ansible --version rather than ansible --version, which may resolve to a different install on your PATH. Print the actual types with {{ some_var | type_debug }} to see what the input really is. And check .venv/bin/ansible-config dump --only-changed for an override — notably ALLOW_BROKEN_CONDITIONALS — that is changing the behaviour under you.

Troubleshooting checklist

  • "Conditionals must have a boolean result." Read the type and the origin line in the message. Convert strings with | bool, add a comparison, or add a predicate such as | length > 0.
  • "Conditional expressions must be strings." A YAML list item was parsed as a mapping because it contains an unquoted colon-space. Quote the whole expression.
  • "Template delimiters are not supported in expressions." Remove {{ }} from when, that, changed_when, failed_when or until.
  • "Type 'range' is unsupported for variable storage." Add | list where the range leaves the expression.
  • A template arrives as literal text. Trust was lost somewhere in the chain. Run once with _ANSIBLE_TEMPLAR_UNTRUSTED_TEMPLATE_BEHAVIOR=warning to locate it.
  • A filter result changed type after the upgrade. The old literal-evaluation pass was converting it for you. Add the conversion you actually want — | list, | string, | int — rather than relying on the result parsing a particular way.

Run your own suite with --syntax-check first, then in check mode against one host, and read the warnings rather than filtering them out; the 2.19 error-handling work means most of these failures now name the file, line, and column that need editing. Note the limits of that dry run — see what check mode actually proves — and note that upstream states error message contents are not stable, so do not grep for these strings in CI.

Related reading

Sources