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.
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.
---
- 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.existsHow 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
- Conditionals (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.
Related guides
- Use when with a variable and the bool filter
- Use when with ansible_facts to skip a task by OS
- Use search to match a pattern anywhere in a string
- Use changed_when to mark when a task changes the system
- Use failed_when to control when a task fails
- Debug a when condition before you skip a task
- Use truthy to test whether a value is true
- Use when with loop to skip items
- Use register to capture task output
- Use when on include_tasks, not import_tasks