To implement conditions in Ansible, we use the when keyword. The keyword takes Boolean expressions based on a value or a variable from previous tasks or facts gathered from the remote hosts.
This guide will teach you how to implement conditions in Ansible playbooks using the when keyword.
Ansible When Conditionals: Basic Usage
The when keyword takes a simple syntax:
Ensure to pass a condition that evaluates to either true or false.
For example:
when: ansible_user_shell" == "/bin/bash"
If you want to combine multiple conditions, you can use logical operators such as and, or, and not.
when: (condition1) or (condition2)
To understand how to use the Ansible when keyword, we will use practical examples.
Example 1
The first example will create a user if the specified user does not exist on the remote host.
- hosts: all
gather_facts: no
become: true
tasks:
- name: checkifdirectoryexist
stat:
path: /home/ubuntu
register: dir
- name: createfileifdirectoryexists
file:
path: /home/ubuntu/file.txt
state: touch
when: dir.stat.exists
The above example starts by checking if the home directory of the ubuntu user is available. We then use the when condition to create a text file if the directory is available.
Example 2
The next example shuts down all the Ubuntu remote hosts using a when condition.
- hosts: all
gather_facts: yes
become: true
tasks:
- name: shutdownUbuntuservers
command: /sbin/shutdown-tnow
when: ansible_facts['os_family']=="Ubuntu"
In the example above, we use gathered facts to evaluate if the servers are from the Ubuntu family. If true, shut down the servers.
Example 3
In the example below, we combine two conditions that use an and operator.
- hosts: all
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: httpd
state: latest
when: (ansible_facts['os_family']=="Debian")and
(ansible_facts['ansible_distribution_major_version']==10)
The example above checks if the hosts are Debian hosts and if the distribution version is equal to Debian 10.
Example 4
We install the Apache webserver in the playbook below if the host family is either a Debian or Ubuntu host.
The playbook uses a logical or operator.
- hosts: all
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: httpd
state: latest
when: (ansible_facts['os_family']=="Debian")or
(ansible_facts['os_family']=="Ubuntu")
Example 5
Consider the playbook below that updates the Nginx server to the latest version by using the not operator.
- hosts: all
- shell: /sbin/nginx-v2>&1
register: version
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: nginx
state: latest
when: ('"nginx/1.19.0"notinversion.stdout')
If the output from the Nginx server is not the current version, install the current version of the package.
Conclusion
In this guide, we discussed how to work with conditionals in Ansible using the when keyword.
Thank you for reading!