The when condition in Ansible enables selective task execution and allows for the creation of conditional playbooks that depend on specific criteria.
This feature is crucial for developing idempotent, reusable automation scripts, as it ensures that actions execute only when the target machines meet all necessary prerequisites.
This article will explain the when condition in Ansible and provide practical examples.

Ansible when Condition Syntax
The when clause consists of one or more key-value pairs placed within a task definition in an Ansible playbook file. The expression (or a list of expressions) in the clause must evaluate to a Boolean True or False value for the task to run.
The image below shows the when clause in an Ansible playbook.

The basic structure involves the when keyword followed by one or more conditional expressions connected using and or or operator:
when: [expression] and|or [expression2] and|or [...]
The [expression] follows the Jinja2 templating language. Ansible evaluates it against facts, variables, or registered results.
How Does Ansible when Condition Work?
Ansible processes tasks sequentially. Before executing any task, the platform evaluates the associated when condition. The evaluation resolves variables and runs comparisons against facts gathered from the target host.
If the expression evaluates to True, Ansible allows the task to proceed. If the result is False, Ansible skips the task and reports the skipped status for that particular action.
When a variable that is referenced in a when condition is undefined, Ansible raises a fatal exception and halts playbook execution. To circumvent this behavior and ensure that conditional logic still executes, the user can apply the Jinja2 | default(…) filter to the variable.
The filter provides a fallback value (e.g., false, "", or []) if the variable is missing, allowing the when expression to successfully evaluate to a Boolean instead of throwing an error.
Below is the syntax for applying the filter:
when: [variable] | default(false)
Ansible when Condition Examples
Conditional logic is crucial for building precise automation that adapts to different environments or host states. The examples in the sections below demonstrate various everyday use cases for the when condition, utilizing different types of variables, facts, and logical operators.
Running Task Based on Ansible Fact
This example shows how to restrict task execution to hosts running a specific operating system family. Ansible will only attempt to install the Nginx package on machines identified as Debian-family machines:
- name: Install NGINX on Debian-based systems
ansible.builtin.apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
Checking for Multiple Conditions
Multiple conditions can be combined using the and operator, which requires all conditions to be met for the task to execute.
In the following example, this operator ensures that a Ubuntu server configuration is changed only when the environment variable is set to production:
- name: Configure production settings on Ubuntu
ansible.builtin.template:
src: config.j2
dest: /etc/app/config.conf
when: ansible_distribution == 'Ubuntu' and environment == 'production'
Using Registered Variable Result
Task output can be captured using the register module, and its properties can then be used in subsequent when conditions.
This task checks whether the previously executed shell command stored in check_service returned a non-zero exit code, indicating an issue:
- name: Check service status
ansible.builtin.shell: /usr/bin/systemctl is-active service_name
register: service_status
ignore_errors: true
- name: Restart service if check failed
ansible.builtin.systemd:
name: service_name
state: restarted
when: service_status.rc != 0
Checking for Variable Presence
Task execution can depend on the definition of a specific variable, preventing errors when optional parameters are missing.
In the example below, the task to create a new user proceeds only if the new_username variable exists for the play or inventory:
- name: Create a new user if variable is defined
ansible.builtin.user:
name: "{{ new_username }}"
state: present
when: new_user_name is defined
Checking for List Membership
The in operator checks whether a variable's value is in a defined list of acceptable values. Ansible executes the following task only if the app_version variable matches one of the stable release identifiers:
- name: Deploy stable application version
ansible.builtin.copy:
src: files/v{{ app_version }}.tar.gz
dest: /opt/app/
when: app_version in ['1.2.0', '2.0.1', '3.1.5']
Checking for Multiple Conditions
The or operator runs a task if at least one of the specified conditions evaluates to True.
The following example task ensures Ansible applies the patch to machines running either CentOS or Red Hat Enterprise Linux:
- name: Apply critical patch to Red Hat-based hosts
ansible.builtin.yum:
name: kernel-patch
state: latest
when: ansible_distribution == 'CentOS' or ansible_distribution == 'RedHat'
Using Comparison Operators on Numeric Facts
Use numeric facts with standard comparison operators like >, <, >=, and <= to create numeric conditions. The task below only proceeds if the system's total memory is greater than 4 gigabytes:
- name: Allocate large memory cache
ansible.builtin.shell: echo "cache_size=4096MB" >> /etc/app.conf
when: ansible_memtotal_mb > 4096
Conclusion
After reading this article, you know how to use the when statement in Ansible. Mastering the statement's syntax and application enables the creation of playbooks that intelligently adapt to target host environments and prior task outcomes.
Next, learn more about Ansible's shell module.

