Ansible when Conditional: Complete Guide with Examples
By Luca Berton · Published 2026-04-03 · Category: installation
Complete guide to Ansible when conditionals. Use when statements with facts, variables, registered results, and complex boolean logic in playbooks.
The when statement is Ansible's conditional — it controls whether a task runs based on variables, facts, registered results, or any Jinja2 expression.
Basic when Syntax
Important: when uses raw Jinja2 expressions — do NOT wrap in {{ }}.
Boolean Conditions
OS and Distribution Conditions
AND / OR Logic
AND (all conditions must be true)
OR (any condition)
Complex combinations
Variable Testing
Registered Variables
when with Loops
when with Blocks
Test Filters
Common Patterns
Skip task in check mode
First run detection
FAQ
Why can't I use {{ }} in when statements?
when already evaluates as a Jinja2 expression. Adding {{ }} would double-evaluate and cause errors. Just use variable names directly.
How do I check if a variable is true/false?
when: my_var checks truthiness (non-empty, non-zero, not None). when: my_var == true checks for boolean True specifically.
Can I use when with include_tasks?
Yes. The condition applies to the include itself — all tasks in the included file will be skipped if the condition is false.
Basic when
Common Conditions
Multiple Conditions (AND)
OR Conditions
Based on Registered Results
Check Variable Content
Conditionals with Loops
Block-Level Conditionals
Version Comparison
File/Path Tests
Common Mistakes
FAQ
How do I negate a condition?
Can I use when with handlers?
Yes — handlers support when, but they only run if notified AND the condition is true.
How do I skip an entire role?
Basic when
Multiple Conditions (AND)
OR Conditions
Check Variable Defined
Registered Results
Boolean Variables
Conditional on Facts
Conditional with Loops
Conditional Blocks
String Tests
FAQ
when vs failed_when vs changed_when?
when controls if a task runs. failed_when controls if a task is considered failed. changed_when controls if a task reports as changed.
Can I use Jinja2 in when?
when already evaluates as Jinja2 — don't wrap in {{ }}. Wrong: when: "{{ x }}". Right: when: x.
How to negate a condition?
Use not: when: not my_var or when: my_var is not defined.
Related Articles • Ansible Template Guide • Ansible Ignore Errors Guide • Ansible Check Mode Guide • Ansible Loops Guide • Ansible Nginx Guide
Category: installation