Conditionals
Learn how to control task executions using conditionals.
Overview
Conditionals are used to control the execution of tasks or playbooks based on specific conditions. They enable us to make our automation responsive to the state of a managed node, the value of a variable, or other factors. Ansible supports conditional statements using the when
keyword, and it’s a powerful tool for creating flexible and adaptive automation workflows.
Working with conditionals
Conditionals are useful in a couple of scenarios. Let’s imagine that we’re responsible for managing a fleet of servers in a large data center, and we need to automate the deployment of a critical software update. However, the update is complex and resource-intensive, so we want to only apply it to a specific subset of servers based on various conditions. We can use conditionals for this kind of scenario.
There are various keywords used to enforce conditions in Ansible, such as:
- The
when
statement - The
failed_when
statement - The
changed_when
statement
The when
statement
The when
statement is used to specify a condition under which a task should be executed. If the condition evaluates to true, the task is executed; otherwise, it is skipped.
As shown below, a relevant example is ensuring the creation of symbolic links between NGINX site ...