Reader small image

You're reading from  Practical Ansible - Second Edition

Product typeBook
Published inSep 2023
PublisherPackt
ISBN-139781805129974
Edition2nd Edition
Right arrow
Authors (3):
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

Fabio Alessandro Locati
Fabio Alessandro Locati
author image
Fabio Alessandro Locati

Fabio Alessandro Locati – commonly known as Fale – is an EMEA associate principal solutions architect at Red Hat, a public speaker, an author, and an open source contributor. His primary areas of expertise are Linux, automation, security, and cloud technologies. Fale has more than 15 years of working experience in IT, with many of them spent consulting for various organizations, including dozens of Fortune 500 companies. Fale has written Learning Ansible 2.7, Learning Ansible 2, and OpenStack Cloud Security, and has been part of the review process of multiple books.
Read more about Fabio Alessandro Locati

Daniel Oh
Daniel Oh
author image
Daniel Oh

Daniel Oh is a principal technical marketing manager at Red Hat. He provides runtimes, frameworks, fast data access, and high-performance messaging in flexible, easy-to-use, cost-effective, open, and collaborative ways. He's also a CNCF ambassador and DevOps Institute ambassador who evangelizes how to design and develop cloud-native serverless microservices and deploy them to multi/hybrid cloud-native platforms based on CNCF projects. Daniel loves to share his developer experiences with DevOps folks in terms of how to evolve traditional microservices to cloud-native, event-driven, and serverless applications via technical workshops, brown bag sessions, hackathons, and hands-on labs across regions at many international conferences.
Read more about Daniel Oh

View More author details
Right arrow

Creating and Consuming Modules

Throughout this book, we have almost constantly referred to and made use of Ansible modules. We have treated these as black boxes – that is to say, we have just accepted that they exist and that they will work in a certain documented manner. However, one of the many great things about Ansible is that it is an open source project, and as such, not only can you view and modify its source code, but you can also develop your own additions. At the time of writing, there are 3,300+ modules available for Ansible, handling everything from simple commands such as copying files and installing packages to configuring highly complex and bespoke networking equipment. This large array of modules has grown out of a genuine need to solve problems with Ansible, and the number included with each release of Ansible increases every time.

Sooner or later, you will come across a specific piece of functionality that doesn’t exist in any of the current Ansible...

Technical requirements

This chapter assumes that you have set up your control host with Ansible, as detailed in Chapter 1, Getting Started with Ansible, and are using the most recent version available – the examples in this chapter were tested with ansible-core version 2.15. This chapter also assumes that you have at least one additional host to test against. Ideally, this should be Linux-based. Although we will give specific examples of hostnames in this chapter, you are free to substitute them with your own hostname and/or IP address. Details of how to do this will be provided in the appropriate places.

The module development work that will be covered in this chapter assumes the presence of a Python 3 development environment on your computer and that you are running either Linux, FreeBSD, or macOS. Where additional Python modules are needed, their installation is documented. The task of building module documentation has some very specific requirements around Python 3.10...

Executing multiple modules using the command line

As this chapter is all about modules and how to create them, let’s recap how to use modules. We’ve done this throughout this book, but we have not drawn attention to some of the specifics related to how they work. One of the key things we have not discussed is how the Ansible engine talks to its modules and vice versa, so let’s explore this now.

As ever, when working with Ansible commands, we need an inventory to run our commands against. For this chapter, as our focus is on the modules themselves, we will use a very simple and small inventory, as shown here:

[frontends]
frt01.example.com
[appservers]
app01.example.com

Now, for the first part of our recap, you can run a module very easily via an ad hoc command and use the -m switch to tell Ansible which module you want to run. Hence, one of the simplest commands you can run is the Ansible ping command, as shown here:

$ ansible -i hosts appservers -m ping...

Reviewing the module index

As discussed in the preceding section, Ansible provides thousands of modules to make it fast and easy to develop playbooks and run them across multiple host machines. How do you go about finding the right module to begin with, though, when there are so many? Fortunately, the Ansible documentation features a well-organized, indexed list of modules that you can consult to find your desired module – this is available here: https://docs.ansible.com/ansible/latest/collections/index_module.html.

Let’s suppose you want to see whether there is a native Ansible module that can help you configure and manage your Amazon Web Services S3 buckets. That’s a fairly precise, well-defined need, so let’s approach this logically:

  1. Begin by opening the index of all modules in your web browser, as discussed previously: https://docs.ansible.com/ansible/latest/collections/index_module.html.
  2. Now, we know that amazon.aws modules are certainly...

Accessing module documentation from the command line

As discussed in the preceding section, the Ansible project prides itself on its documentation, and making this documentation readily accessible is an important part of the project itself. Now, suppose you are working on an Ansible task (in a playbook, role, or even an ad hoc command) and you are in a data center environment where you only have access to the shell of the machine you are working on. How would you get access to the Ansible documentation?

Fortunately, part of the Ansible installation that we have not discussed yet is the ansible-doc tool, which is installed as standard along with the familiar ansible and ansible-playbook executables. The ansible-doc command includes a complete (text-based) library of documentation for all the modules that ship with the version of Ansible you have installed. This means that the very information you need to work with modules is at your fingertips, even if you are in the middle of a...

Module return values

As we discussed earlier in this chapter, Ansible modules return their results as structured data, formatted behind the scenes in JSON. You came across this return data in the previous example, both in the form of an exit code and where we used the register keyword to capture the results of a task in an Ansible variable. In this section, we shall explore how to discover the return values for an Ansible module so that we can work with them later on in a playbook, for example, with conditional processing (see Chapter 4, Playbooks and Roles).

Due to conserving space, we shall choose what is perhaps one of the simplest Ansible modules to work with when it comes to return values – the ping module.

Without further ado, let’s use the ansible-doc tool that we learned about in the previous section and see what this says about the return values for this module:

$ ansible-doc ping

If you scroll to the bottom of the output from the preceding command...

Developing custom modules

Now that we’re familiar with modules, how to call them, how to interpret their results, and how to find documentation on them, we can make a start on writing a simple module. Although this will not include the deep and intricate functionality of many of the modules that ship with Ansible, it is hoped that this will give you enough information to proceed with confidence when you build out your own, more complex, ones.

One important point to note is that Ansible is written in Python 3, and as such, so are its modules. As a result, you will need to write your module in Python 3; to get started with developing your own module, you will need to make sure you have Python 3 and a few essential tools installed. If you are already running Ansible on your development machine, you probably have the required packages installed, but if you are starting from scratch, you will need to install Python 3, the Python 3 package manager (pip3), and perhaps some other...

Summary

Modules are the very lifeblood of Ansible – without them, Ansible could not perform all of the complex and varied tasks it performs so well across a wide variety of systems. By being an open source project, it is incredibly easy to extend the functionality of Ansible by yourself, and in this chapter, we explored how you can, with a little Python knowledge, write a custom module from scratch. Ansible is, at the time of writing, incredibly feature-rich, but this ease of customization and extension makes Ansible virtually limitless in terms of its potential, especially given the power and popularity of Python as a programming language.

In this chapter, we started with a recap of how to execute multiple modules using the command line. We then explored the process of interrogating the current module index, as well as how to obtain documentation about modules to evaluate their suitability for our needs, regardless of whether we have an active internet connection or not...

Questions

Answer the following questions to test your knowledge of this chapter:

  1. Which command line can be passed down as a parameter to a module?
    1. ansible dbservers -m command "/bin/echo 'hello modules'"
    2. ansible dbservers -m command -d "/bin/echo 'hello modules'"
    3. ansible dbservers -z command -a "/bin/echo 'hello modules'"
    4. ansible dbservers -m command -a "/bin/echo 'hello modules'"
    5. ansible dbservers -a "/bin/echo 'hello modules'"
  2. Which of the following practices is not recommended when you create a custom module and address exceptions?
    1. Design a custom module simply and never provide a traceback to the user, if you can avoid it.
    2. Fail your module code quickly, and verify that you are providing helpful and understandable exception messages.
    3. Only display error messages for the most relevant exceptions, rather than all possible errors.
    4. Ensure that your module documentation is relevant and...

Further reading

To learn more about the topics that were covered in this chapter, take a look at the following resources:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Practical Ansible - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781805129974
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 €14.99/month. Cancel anytime

Authors (3)

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
Fabio Alessandro Locati

Fabio Alessandro Locati – commonly known as Fale – is an EMEA associate principal solutions architect at Red Hat, a public speaker, an author, and an open source contributor. His primary areas of expertise are Linux, automation, security, and cloud technologies. Fale has more than 15 years of working experience in IT, with many of them spent consulting for various organizations, including dozens of Fortune 500 companies. Fale has written Learning Ansible 2.7, Learning Ansible 2, and OpenStack Cloud Security, and has been part of the review process of multiple books.
Read more about Fabio Alessandro Locati

author image
Daniel Oh

Daniel Oh is a principal technical marketing manager at Red Hat. He provides runtimes, frameworks, fast data access, and high-performance messaging in flexible, easy-to-use, cost-effective, open, and collaborative ways. He's also a CNCF ambassador and DevOps Institute ambassador who evangelizes how to design and develop cloud-native serverless microservices and deploy them to multi/hybrid cloud-native platforms based on CNCF projects. Daniel loves to share his developer experiences with DevOps folks in terms of how to evolve traditional microservices to cloud-native, event-driven, and serverless applications via technical workshops, brown bag sessions, hackathons, and hands-on labs across regions at many international conferences.
Read more about Daniel Oh