Ansible Conditionals and Jinja Expressions
when: decides whether a task runs, per host and per loop item. It takes a Jinja2 expression without the usual braces, which is the source of the best-known mistake in Ansible - and one that current versions handle differently from every tutorial written about it. This covers the three things you branch on and the quoting rule.
Plays and Playbooks Guide 14 of 45 Intermediate
- OSUbuntu 26.04 LTS
- ansible-core2.20.1
- Python3.14.4
- TimeAbout 15 min
when: "{{ var }}" was historically always true, because the braces rendered to a non-empty string. On ansible-core 2.20 it evaluates correctly and emits a deprecation warning: conditionals surrounded by templating delimiters are removed in 2.23. So the old silent bug is now a loud warning, and the advice is unchanged - write the expression bare.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| ANS-CTL01 | 192.168.0.36 | Ubuntu 26.04 LTS | Ansible Control Node | 2 Core | 3 GB | 50 GB |
| ANS-A01 | 192.168.0.37 | Ubuntu 26.04 LTS | Managed Node (group: web) | 2 Core | 3 GB | 50 GB |
| ANS-B01 | 192.168.0.38 | Ubuntu 26.04 LTS | Managed Node (group: db) | 2 Core | 3 GB | 50 GB |
This guide includes
Use this when a task should run on some hosts and not others. This matters because when: is already a Jinja expression - wrapping it in braces is the famous mistake, and it quietly makes every condition true.
- using
when:against a fact - using it against something you registered, in the probe-then-act shape
- combining conditions, where a list of them means AND
- meeting the braces to avoid, and seeing exactly why they break the test
Before you start
- A control node configured as shown in the first step.
- The session runs four small playbooks and changes nothing on the managed nodes.
-
The configuration this guide assumes
-
when against a fact
-
when against something you registered
-
Combining conditions
-
The braces to avoid