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

Subscribe for updates

Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.

By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.

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

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

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