BacklogZero®

Ansible in a Minute · Ansible Core ·

Use when to run a task only if a condition is true

Short answer

Use when to skip a task unless a condition evaluates to true.

Ansible in a Minute — when

Request

run a debug task only when a registered file exists

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Run a debug task only when a registered file exists
  hosts: all
  gather_facts: true
  tasks:
    - name: Register file existence
      ansible.builtin.stat:
        path: /path/to/your/file
      register: file_stat

    - name: Run debug task if file exists
      ansible.builtin.debug:
        msg: "File exists"
      when: file_stat.stat.exists

How it works

when evaluates a Jinja2 expression. If the expression is false, Ansible skips the task. Use facts or registered results in the expression.

When to use it

  • Skipping work on hosts that already meet the desired state
  • Branching on facts such as OS family or package presence

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-05

Notes

Keep the when expression explicit. Prefer registered results or facts over unclear variable names.

Reference

Try it with BacklogZero

Ask BacklogZero to generate this automation for your environment.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use when to run a task only if a condition is true · Level Up Labs