Reader small image

You're reading from  Mastering Ansible, 4th Edition - Fourth Edition

Product typeBook
Published inDec 2021
PublisherPackt
ISBN-139781801818780
Edition4th Edition
Right arrow
Authors (2):
James Freeman
James Freeman
author image
James Freeman

James Freeman is an accomplished IT professional with over 25 years' experience in the technology industry. He has more than a decade of first-hand experience in solving real-world enterprise problems in production environments using Ansible, open source, and AWS. As part of this work, he frequently introduces Ansible as a new technology to businesses and CTOs for the first time. In addition, he has co-authored five books and one video training course on Ansible, facilitated bespoke Ansible workshops and training sessions, and presented at both international conferences and meetups on Ansible.
Read more about James Freeman

Jesse Keating
Jesse Keating
author image
Jesse Keating

Jesse Keating is an accomplished Ansible user, contributor, and presenter. He has been an active member of the Linux and open source community for over 15 years. He has firsthand experience involving a variety of IT activities, software development, and large-scale system administration. He has presented at numerous conferences and meetups, and has written many articles on a variety of topics.
Read more about Jesse Keating

View More author details
Right arrow

Chapter 7: Controlling Task Conditions

Ansible is a system for running tasks on one or more hosts, and ensuring that operators understand whether changes have occurred (and indeed whether any issues were encountered). As a result, Ansible tasks result in one of four possible statuses: okchangedfailed, or skipped. These statuses perform a number of important functions.

From the perspective of an operator running an Ansible playbook, they provide an overview of the Ansible run that has been completed—whether anything changed or not and whether there were any failures that need addressing. In addition, they determine the flow of the playbook—for example, if a task results in a changed status, we might want to perform a restart of the service, but otherwise leave it running. Ansible possesses all the necessary functions to achieve this.

Similarly, if a task results in a failed status, the default behavior of Ansible is not...

Technical requirements

To follow the examples presented in this chapter, you will need a Linux machine running Ansible 4.3 or newer. Almost any flavor of Linux should do—for those interested in specifics, all the code presented in this chapter was tested on Ubuntu Server 20.04 LTS unless stated otherwise, and on Ansible 4.3. The example code that accompanies this chapter can be downloaded from GitHub at this URL: https://github.com/PacktPublishing/Mastering-Ansible-Fourth-Edition/tree/main/Chapter07.

Check out the following video to see the Code in Action: https://bit.ly/3AVXxME.

Defining a failure

Most modules that ship with Ansible have differing criteria for what constitutes an error. An error condition is highly dependent upon the module and what the module is attempting to accomplish. When a module returns an error, the host will be removed from the set of available hosts, preventing any further tasks or handlers from being executed on that host. Furthermore, the ansible-playbook and ansible executables will exit with a non-zero exit code to indicate failure. However, we are not limited by a module's opinion of what an error is. We can ignore errors or redefine an error condition.

Ignoring errors

A task condition named ignore_errors is used to ignore errors. This condition is a Boolean, meaning that the value should be something Ansible understands to be true, such as yesontrue, or 1 (string or integer).

To demonstrate how to use ignore_errors, let's create...

Defining a change

Similar to defining a task failure, it is also possible to define what constitutes a changed task result. This capability is particularly useful with the ansible.builtin.command family of modules (commandshellraw, and script). Unlike most other modules, the modules of this family do not have an inherent idea of what a change may be. In fact, unless otherwise directed, these modules only result in failedchanged, or skipped. There is simply no way for these modules to assume a changed versus unchanged condition, as they cannot be expected to understand or interpret every possible shell command you might execute using them.

The changed_when condition allows a playbook author to instruct a module on how to interpret a change. Just like failed_whenchanged_when performs a test to generate a Boolean result. Frequently, the tasks used with changed_when are commands that will exit...

Error recovery

While error conditions can be narrowly defined, there will be times when real errors happen. Ansible provides a method to react to true errors, a method that allows running additional tasks when an error occurs, defining specific tasks that always execute even if there was an error, or even both. This method is the block feature.

The blocks feature, introduced with Ansible version 2.0, provides some additional structure to related sets of play task. Blocks can group tasks together into a logical unit, which can have task controls applied to the unit (or block) as a whole. In addition, a block of tasks can have optional rescue and always sections, which execute on condition of an error and regardless of the error state, respectively. We will explore how these work in the following two sections.

Using the rescue section

The rescue section of a block defines a logical unit of tasks that will be executed...

Iterative tasks with loops

Loops deserve a special mention in this chapter. So far, we have focused on controlling the flow of a playbook in a top-to-bottom fashion—we have changed the various conditions that might be evaluated as the playbook runs, and we have also focused on creating concise, efficient code. What happens, however, if you have a single task, but need to run it against a list of data; for example, creating several user accounts, directories, or indeed something more complex?

Looping changed in Ansible 2.5—prior to this, loops were generally created with keywords such as with_items and you may still see this in legacy code. Although some backward compatibility remains, it is advisable to move to the newer loop keyword instead.

Let's take a simple example—we need to create two directories. Create loop.yaml as follows:

---
- name: looping demo
  hosts: localhost
  gather_facts: false...

Summary

In this chapter, you learned that it is possible to define specifically how Ansible perceives a failure or a change when a specific task is run, how to use blocks to gracefully handle errors and perform cleanup, and how to write tight, efficient code using loops.

As a result, you should now be able to alter any given task to provide specific conditions under which Ansible will fail it or consider a change successful. This is incredibly valuable when running shell commands, as we have demonstrated in this chapter, and also serves when defining specialized use cases for existing modules. You should also now be able to organize your Ansible tasks into blocks, ensuring that if failures do occur, recovery actions can be taken that would otherwise not need to be run. Finally, you should now be able to write tight, efficient Ansible playbooks using loops, removing the need for repetitive code and lengthy, inefficient playbooks.

In the next chapter, we'll explore...

Questions

  1. By default, Ansible will stop processing further tasks for a given host after the first failure occurs:

    a) True

    b) False

  2. The ansible.builtin.command and ansible.builtin.shell modules' default behavior is to only ever give a task status of changed or failed:

    a) True

    b) False

  3. You can store the results from a task using which Ansible keyword?

    a) store:

    b) variable:

    c) register:

    d) save:

  4. Which of the following directives can be used to change the failure condition of a task?

    a) error_if:

    b) failed_if:

    c) error_when:

    d) failed_when:

  5. You can combine multiple conditional statements in Ansible using which of the following?

    a) and

    b) or

    c) The YAML list format (which works the same as a logical AND)

    d) All of the above

  6. Changes can be suppressed with which of the following?

    a) suppress_changed: true

    b) changed_when: false

    c) changed: false

    d) failed_when: false

  7. In a block section, all tasks are executed in order on all hosts:

    a) Until the first error occurs

    b) Regardless...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Ansible, 4th Edition - Fourth Edition
Published in: Dec 2021Publisher: PacktISBN-13: 9781801818780
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Authors (2)

author image
James Freeman

James Freeman is an accomplished IT professional with over 25 years' experience in the technology industry. He has more than a decade of first-hand experience in solving real-world enterprise problems in production environments using Ansible, open source, and AWS. As part of this work, he frequently introduces Ansible as a new technology to businesses and CTOs for the first time. In addition, he has co-authored five books and one video training course on Ansible, facilitated bespoke Ansible workshops and training sessions, and presented at both international conferences and meetups on Ansible.
Read more about James Freeman

author image
Jesse Keating

Jesse Keating is an accomplished Ansible user, contributor, and presenter. He has been an active member of the Linux and open source community for over 15 years. He has firsthand experience involving a variety of IT activities, software development, and large-scale system administration. He has presented at numerous conferences and meetups, and has written many articles on a variety of topics.
Read more about Jesse Keating