TExcelTAD
Home › Configuration Management: Ansible › Conditionals with when

Conditionals with when

when: runs a task only if a Jinja2 expression is true. Like assert's that:, it takes a bare expression without braces.

yaml
- name: Only on Debian-family hosts
  ansible.builtin.apt:
    name: unattended-upgrades
  when: ansible_facts['os_family'] == "Debian"

Common condition shapes

Condition Meaning
when: app_env == "prod" comparison
when: app_debug | bool a variable that may be the string "yes"/"false" (from -e or INI inventories), so convert it
when: tls_cert is defined variable exists
when: result is changed / is failed / is succeeded / is skipped test a registered result
when: "'web' in group_names" the host is in a group (quote the whole thing: it starts with a quote)
when: ansible_facts['memtotal_mb'] > 4096 numeric
when: with a list all items must be true (AND)
when: a or b OR, written explicitly

A worked example

bash · try it yourself
cat > ansible.cfg <<'INI'
[defaults]
inventory = hosts.ini
interpreter_python = auto_silent
forks = 1
INI
cat > hosts.ini <<'INI'
[web]
web1 ansible_connection=local app_env=prod tls_enabled=true
web2 ansible_connection=local app_env=staging tls_enabled=false

[db]
db1 ansible_connection=local app_env=prod
INI
cat > cond.yml <<'YML'
- name: Conditions
  hosts: all
  gather_facts: false
  tasks:
    - name: Production only
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} is production"
      when: app_env == "prod"

    - name: Web servers with TLS (INI values are strings, hence | bool)
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} serves HTTPS"
      when:
        - "'web' in group_names"
        - tls_enabled | bool

    - name: Hosts without a TLS setting
      ansible.builtin.debug:
        msg: "{{ inventory_hostname }} has no tls_enabled"
      when: tls_enabled is not defined
YML
ansible-playbook cond.yml | grep -E '^(TASK|ok|skipping)'
TASK [Production only] *********************************************************
ok: [web1] => {
skipping: [web2]
ok: [db1] => {
TASK [Web servers with TLS (INI values are strings, hence | bool)] *************
ok: [web1] => {
skipping: [web2]
skipping: [db1]
TASK [Hosts without a TLS setting] *********************************************
skipping: [web1]
skipping: [web2]
ok: [db1] => {

Without | bool, the string "false" would be truthy, and web2 would wrongly serve HTTPS. Since ansible-core 2.19, Ansible is stricter here: a condition must evaluate to a real boolean, so when: tls_enabled with a string value fails instead of guessing. Convert explicitly.

bash · try it yourself
cat > strict.yml <<'YML'
- name: A string used as a condition
  hosts: localhost
  gather_facts: false
  vars:
    tls_enabled: "false"
  tasks:
    - name: Serve HTTPS
      ansible.builtin.debug:
        msg: https on
      when: tls_enabled
YML
ansible-playbook strict.yml 2>/dev/null | grep '^fatal'
fatal: [localhost]: FAILED! => {"msg": "Task failed: A 'when' expression failed: Conditional result (True) was derived from value of type 'str' at '/home/learner/strict.yml:5:18'. Conditionals must have a boolean result."}

The setting ALLOW_BROKEN_CONDITIONALS brings the old behaviour back while you migrate old playbooks; the real fix is | bool.

Conditions on registered results

bash · try it yourself
cat > reg.yml <<'YML'
- name: Act on earlier results
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Write the config
      ansible.builtin.copy:
        dest: app.conf
        content: "workers=4\n"
        mode: "0644"
      register: cfg

    - name: Restart only if the config changed
      ansible.builtin.debug:
        msg: restarting
      when: cfg is changed

    - name: Is a legacy file present?
      ansible.builtin.stat:
        path: legacy.conf
      register: legacy

    - name: Migrate the legacy file
      ansible.builtin.debug:
        msg: migrating legacy.conf
      when: legacy.stat.exists
YML
ansible-playbook reg.yml | grep -E '^(ok|changed|skipping)|"msg"'
echo "=== second run"
ansible-playbook reg.yml | grep -E '^(ok|changed|skipping)|"msg"'
changed: [localhost]
ok: [localhost] => {
    "msg": "restarting"
ok: [localhost]
skipping: [localhost]
=== second run
ok: [localhost]
skipping: [localhost]
ok: [localhost]
skipping: [localhost]

Using when: cfg is changed for a restart works, but a handler is usually cleaner: it also catches changes from several tasks and runs once.

when on blocks, roles and imports

when: on a block, import_tasks or a role in roles: is copied to every task inside: each one evaluates the condition again. With include_tasks / include_role, the condition is evaluated once, on the include itself. That difference matters when a task inside changes the variable the condition uses; Imports & Includes shows it.

Test yourself

An INI inventory sets debug=false. What is the safe condition?

  1. when: debug
  2. when: debug | bool
  3. when: "{{ debug }}"
  4. when: debug == False

What does a list under when: mean?

  1. Any item may be true (OR)
  2. All items must be true (AND)
  3. The first item only
  4. A loop

How do you check whether a registered task changed something?

  1. when: result.changed == 'yes'
  2. when: result is changed
  3. when: changed
  4. when: result.rc