Skip to main content

Ansible Complex Conditional Usage (Variables, Conditionals, Error Handling)

Hands-On Lab

 

Photo of Rob Marti

Rob Marti

Linux Training Architect I in Content

Length

01:00:00

Difficulty

Intermediate

As with any technology, there's going to be errors or things that don't go exactly as planned. Learning how to handle errors as they happen, and building your playbooks to handle errors in a graceful fashion, is an important skill to have. This lab will help reinforce some of the ways to do this.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Ansible Complex Conditional Usage (Variables, Conditionals, Error Handling)

Introduction

As with any technology, there's going to be errors or things that don't go exactly as planned. Learning how to handle errors as they happen, and building your playbooks to handle errors in a graceful fashion, is an important skill to have. This lab will help reinforce some of the ways to do this.

The Scenario

Our backup team wants us to install their backup package everywhere in the environment, and make sure that there's an archive file for them to back up, even if it's empty.

We know that the backup team's repository server has a very low uptime. We need to write our playbook so that installing the linuxacademy_backup_package will not cause the entire playbook to fail. In addition, we have to check and make sure that /root/archive.tar exists, and then create it if it doesn't.

Logging In

Use the credentials provided on the hands-on lab page to get into Server1 to begin with. Since we need root privileges, let's just run sudo -i right off and become root.

Install the linuxacademy_backup_package, Accounting for the Repository or Package Not Being Available

Create the playbook (vim contitional.yml) and create a task to install the package:

---
#Conditional Playbook

- name: Conditional Playbook
  hosts: all
  become: yes

  tasks:
   - name: Install backup package
     yum:
      name: linuxacademy_backup_package
      state: present
     ignore_errors: true

Check for the Existence of /root/archive.tar and Create It If It Doesn't

This part of the playbook should look something like this:

   - name: Check for archive file
     command: ls /root/archive.tar
     register: check_result
     ignore_errors: true
   - name: Touch archive file
     file:
      path: /root/archive.tar
      state: touch
     when: check_result is failed

Run the Playbook

Now let's see what happens when we run this:

ansible-playbook conditional.yml

Conclusion

We'll see errors, but the playbook keeps on going, ignoring them. That's what we wanted. Congratulations!