// Tutorial //

How To Use Conditionals in Ansible Playbooks

Published on April 15, 2021 · Updated on April 14, 2021
Default avatar

By Erika Heidi

Developer Advocate

How To Use Conditionals in Ansible Playbooks

In Ansible, you can define conditions that will be evaluated before a task is executed. When a condition is not met, the task is then skipped. This is done with the when keyword, which accepts expressions that are typically based on a variable or a fact.

The following example defines two variables: create_user_file and user. When the create_user_file is evaluated to true, a new file will be created in the home directory of the user defined by the user variable:

Create a new file called playbook-04.yml in your ansible-practice directory:

  1. nano ~/ansible-practice/playbook-04.yml

Then add the following lines to the new playbook file:

~/ansible-practice/playbook-04.yml
---
- hosts: all
  vars:
    - create_user_file: yes
    - user: sammy  
  tasks:
    - name: create file for user
      file:
        path: /home/{{ user }}/myfile
        state: touch
      when: create_user_file

Save and close the file when you’re done editing its contents.

To execute this playbook on servers from your inventory file, run ansible-playbook with the same connection arguments you’ve used before when running other playbooks in this series. Again, we’ll be using an inventory file named inventory and the sammy user to connect to the remote servers:

  1. ansible-playbook -i inventory playbook-04.yml -u sammy

When the condition is met, you’ll see a changed status in the play output:

Output
... TASK [create file for user] ***************************************************************************** changed: [203.0.113.10] ...

If you change the value of create_user_file to no, the condition will be evaluated to false. In this case, you’ll see a skipping status in the play output, indicating that the task was not executed:

Output
... TASK [create file for user] ***************************************************************************** skipping: [203.0.113.10] ...

A common use for conditionals in the context of Ansible playbooks is to combine them with register, a keyword that creates a new variable and assigns it with the output obtained from a command. This way, you can use any external command to evaluate the execution of a task.

One important thing to notice is that, by default, Ansible will interrupt a play if the command you’re using to evaluate a condition fails. For that reason, you’ll need to include an ignore_errors directive set to yes in said task, and this will make Ansible move on to the next task and continue the play.

The following example will only create a new file in the user home directory in case that file doesn’t exist yet, which we’ll test with an ls command. If the file exists, however, we’ll show a message using the debug module.

Create a new file called playbook-05.yml in your ansible-practice directory:

  1. nano ~/ansible-practice/playbook-05.yml

Then add the following content to the new playbook file:

~/ansible-practice/playbook-05.yml
---
- hosts: all
  vars:
    - user: sammy
  tasks:
    - name: Check if file already exists
      command: ls /home/{{ user }}/myfile
      register: file_exists
      ignore_errors: yes

    - name: create file for user
      file:
        path: /home/{{ user }}/myfile
        state: touch
      when: file_exists is failed

    - name: show message if file exists
      debug:
        msg: The user file already exists.
      when: file_exists is succeeded

Save and close the file when you’re done.

Then, run ansible-playbook with the same connection arguments from the previous examples. Here, we’re using an inventory file named inventory and a user named sammy, but you should change these values accordingly:

  1. ansible-playbook -i inventory playbook-05.yml -u sammy

The first time you run this playbook, the command will fail because the file doesn’t exist in that path. The task that creates the file will then be executed, while the last task will be skipped:

...
[secondary_label Output]

TASK [Check if file already exists] *********************************************************************
fatal: [203.0.113.10]: FAILED! => {"changed": true, "cmd": ["ls", "/home/sammy/myfile"], "delta": "0:00:00.004258", "end": "2020-10-22 13:10:12.680074", "msg": "non-zero return code", "rc": 2, "start": "2020-10-22 13:10:12.675816", "stderr": "ls: cannot access '/home/sammy/myfile': No such file or directory", "stderr_lines": ["ls: cannot access '/home/sammy/myfile': No such file or directory"], "stdout": "", "stdout_lines": []}
...ignoring

TASK [create file for user] *****************************************************************************
changed: [203.0.113.10]

TASK [show message if file exists] **********************************************************************
skipping: [203.0.113.10]
... 

From the output, you can see that the create file for user task caused a change in the server, which means the file was created. Now, run the playbook again and you’ll get a different result:

  1. ansible-playbook -i inventory playbook-05.yml -u sammy
Output
... TASK [Check if file already exists] ********************************************************************* changed: [203.0.113.10] TASK [create file for user] ***************************************************************************** skipping: [203.0.113.10] TASK [show message if file exists] ********************************************************************** ok: [203.0.113.10] => { "msg": "The user file already exists." } ...

If you’d like to learn more about using conditionals in Ansible playbooks, please refer to the official documentation.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up now

Tutorial Series: How To Write Ansible Playbooks

Ansible is a modern configuration management tool that doesn’t require the use of an agent software on remote nodes, using only SSH and Python to communicate and execute commands on managed servers. This series will walk you through the main Ansible features that you can use to write playbooks for server automation. At the end, we’ll see a practical example of how to create a playbook to automate setting up a remote Nginx web server and deploy a static HTML website to it.

About the authors
Default avatar

Developer Advocate

Dev/Ops passionate about open source, PHP, and Linux.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click here to sign up and get $200 of credit to try our products over 60 days!
Try DigitalOcean for free