Ansible Conditions


In an ansible playbook, we sometimes need to execute different tasks depending on the value of a variable or the value of the return variable of a previous task. You may want to perform a certain set of tasks if the value of the variable is less than a value and a different set of tasks if the value of the variable is greater. You can achieve this with Ansible conditions


In this guide, we will demonstrate how to use various when conditional statements.

Using ‘when’ conditional statement

Ansible uses Jinja2 tests and filters in conditionals.

We are going to use the ‘when’ conditional statement to create a file in the playbook as shown:


- 
  name: this is our first play.
  hosts: webserver1
  vars: 
    age: 17
  tasks: 
    - 
      name: 'creating file using variable'
      command: touch /tmp/18.txt
      when: age == 18


The value of var age is 17 which is not satisfying the when condition age =18, hence the task ‘creating the file using variable’ will not be executed.


When you run the playbook, you’ll get the output below-

ansible-conditions



No file is created on webserver1 -

ansible-conditions



Now, let's modify the playbook and change the value of var age = 18 to satisfy the when condition and run the playbook again.


- 
  name: this is our first play.
  hosts: webserver1
  vars: 
    age: 18
  tasks: 
    - 
      name: 'creating file using variable'
      command: touch /tmp/18.txt
      when: age == 18

Output after executing this playbook - 


ansible-conditions


Verify the same on webserver1 -

ansible-conditions


Using multiple ‘when’ conditional statement


Consider below playbook2.yml -

- 
  name: this is our first play.
  hosts: webserver1
  vars: 
    age: 19
  tasks: 
    - 
      name: 'creating file using variable'
      command: touch /tmp/18.txt
      when: age == 18
    - 
      name: 'creating file using variable'
      command: touch /tmp/grater_then_18.txt
      when: age > 18


Here we have 2 conditions. First condition is not true as the age == 18 and second is true because age > 18


When you run the playbook, you’ll get the output below-