Handling Different Operating Systems
Traditionally, you might maintain separate playbooks for different operating systems. For instance, one playbook for Debian-based systems using APT and another for Red Hat-based systems using YUM. Consider the following example for Debian systems:Combining Tasks with Conditionals
Ansible automatically populates the built-in variableansible_os_family with the operating system type (e.g., Debian, RedHat, or SUSE). By using the when clause, you can conditionally execute tasks based on this variable. The following single playbook demonstrates this concept:
Ensure that the
ansible_os_family and ansible_distribution_version facts are correctly set in your inventory and gathered before executing these tasks.Using Conditionals in Loops
In some cases, you may need to install multiple packages based on a specific attribute. For example, if you have a list of packages with arequired property, you can loop through them and install only those marked as required. See the example below:
packages list and uses the condition when: item.required to confirm that only the necessary packages are installed.
Conditionals Based on Task Output
Another practical scenario involves triggering subsequent tasks based on the output of a preceding task. For example, you might want to monitor a service and send an email alert if it is found to be down. The following playbook demonstrates this approach:service httpd status command is captured using the register keyword. The subsequent task checks if the service status includes the word “down” and sends an alert if the condition is met.
Always validate the output captured from commands before using string methods like
find to avoid unexpected behavior.Summary Table of Conditionals Use Cases
| Use Case | Description | Example Module/Directive |
|---|---|---|
| OS-Specific Installation | Install packages based on the OS family | apt for Debian, yum for Red Hat/SUSE |
| Conditional Package Installation in Loops | Iterate over a list and install packages based on a condition | loop with when clause |
| Conditional Execution Based on Task Output | Trigger follow-up tasks dependent on the result of a previous task | register, when with string method checks |