Ansible Conditionals

Conditionals :

In a playbook, you may want to execute different tasks, or have different goals, depending on the value of a fact , a variable, or the result of a previous task. You may want the value of some variables to depend on the value of other variables. Or you may want to create additional groups of hosts based on whether the hosts match other criteria. You can do all of these things with conditionals.

Ansible uses Jinja2 tests and filters in conditionals. Ansible supports all the standard tests and filters, and adds some unique ones as well.

Basic format of using conditional :


In the above example we have set up a condition that install a nginx package using apt module when the OS Family is Debian and version is 10.04. In the second condition, nginx package will be installed when OS Family is either Redhat or SUSE.

“When Conditional” is the most commonly used Conditional

Sometimes you will want to skip a particular step on a particular host. This could be something as simple as not installing a certain package if the operating system is a particular version, or it could be something like performing some cleanup steps if a filesystem is getting full.

This is easy to do in Ansible with the when clause, which contains a raw Jinja2 expression without double curly braces. It’s actually pretty simple:

You can also use parentheses to group conditions:


In below example, we have used variable, loop and when conditional in a single playbook. Basically in this playbook a loop of variables will execute and only those packages will be installed where ‘required=true‘ is mentioned.

Before executing ansible playbook :


Post executing playbook :

Use of conditionals with register :

Check out – 

“What is Dictionary” and How to use Dict{} in python 


1 thought on “Ansible Conditionals”

Leave a Reply

Your email address will not be published. Required fields are marked *