Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Practical Ansible - Second Edition

You're reading from  Practical Ansible - Second Edition

Product type Book
Published in Sep 2023
Publisher Packt
ISBN-13 9781805129974
Pages 420 pages
Edition 2nd Edition
Languages
Authors (3):
James Freeman James Freeman
Profile icon James Freeman
Fabio Alessandro Locati Fabio Alessandro Locati
Profile icon Fabio Alessandro Locati
Daniel Oh Daniel Oh
Profile icon Daniel Oh
View More author details

Table of Contents (21) Chapters

Preface 1. Part 1:Learning the Fundamentals of Ansible
2. Chapter 1: Getting Started with Ansible 3. Chapter 2: Understanding the Fundamentals of Ansible 4. Chapter 3: Defining Your Inventory 5. Chapter 4: Playbooks and Roles 6. Part 2:Expanding the Capabilities of Ansible
7. Chapter 5: Creating and Consuming Modules 8. Chapter 6: Creating and Consuming Collections 9. Chapter 7: Creating and Consuming Plugins 10. Chapter 8: Coding Best Practices 11. Chapter 9: Advanced Ansible Topics 12. Part 3:Using Ansible in an Enterprise
13. Chapter 10: Network Automation with Ansible 14. Chapter 11: Container and Cloud Management 15. Chapter 12: Troubleshooting and Testing Strategies 16. Chapter 13: Getting Started with Ansible Automation Controller 17. Chapter 14: Execution Environments 18. Assessments 19. Index 20. Other Books You May Enjoy

Playbooks and Roles

So far in this book, we have worked mostly with ad hoc Ansible commands for simplicity and to help you to understand the fundamentals. However, the lifeblood of Ansible is most certainly the playbook, which is a logical organization of tasks (think ad hoc commands) in a structure that creates a useful outcome. This might be to deploy a web server on a newly built virtual machine, or it might be to apply a security policy. It might even involve handling the whole build process for a virtual machine! The possibilities are endless. Ansible playbooks, as we have already covered, are designed to be simple to write and easy to read – they are intended to be self-documenting and, as such, will form a valuable part of your IT processes.

In this chapter, we will explore playbooks in greater depth, from the basics of their creation to more advanced concepts such as running tasks in loops and blocks, performing conditional logic, and – perhaps one of the most...

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 8.0 and ansible-core 2.15. This chapter also assumes that you have at least one additional host to test against, and 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 hostnames and/or IP addresses, and details of how to do this will be provided in the appropriate places.

The code bundle for this chapter is available here: https://github.com/PacktPublishing/Practical-Ansible-Second-Edition/tree/main/Chapter%204.

Understanding the playbook framework

A playbook allows you to manage multiple configurations and complex deployments on many machines simply and easily. This is one of the key benefits of using Ansible for the delivery of complex applications. With playbooks, you can organize your tasks in a logical structure, as tasks are (generally) executed in the order they are written, allowing you to have a good deal of control over your automation processes. With that said, it is possible to perform tasks asynchronously, so where tasks are not executed in sequence, we will highlight this. Our goal is that once you complete this chapter, you will understand the best practices to write your own Ansible playbooks.

Although YAML format is easy to read and write, it is very pedantic when it comes to spacing. For example, you cannot use tabs to set indentation even though on the screen a tab and four spaces might look identical – in YAML, they are not. We recommend that you adopt an editor...

Understanding roles – the playbook organizer

Roles are designed to enable you to efficiently and effectively reuse Ansible code. They always follow a known structure and often will include sensible default values for variables, error handling, handlers, and so on. Taking our Apache installation example from the previous chapter, we know that this is something that we might want to do over and over again, perhaps with a different configuration file each time, and perhaps with a few other tweaks on a per-server (or per-inventory group) basis. In Ansible, the most efficient way to support the reuse of this code in this way would be to create it as a role.

The process of creating roles is in fact very simple – Ansible will (by default) look within the same directory that you are running your playbook from for a roles/ directory, and in here, you will create one subdirectory for each role. The role name is derived from the subdirectory name. There is no need to create complex...

Using conditions in your code

In most of our examples so far, we have created simple sets of tasks that always run. However, as you generate tasks (whether in roles or playbooks) that you want to apply to a wider array of hosts, sooner or later, you will want to perform some kind of conditional action. This might be to only perform a task in response to the results of a previous task, or it might be to only perform a task in response to a specific fact gathered from a managed node. In this section, we will provide some practical examples of conditional logic to apply to your Ansible tasks to demonstrate how to use this feature.

As ever, we’ll need an inventory to get started, and we’ll reuse the inventory we have used throughout this chapter:

[frontends]
web01.example.org https_port=8443
web02.example.org http_proxy=proxy.example.org
[frontends:vars]
ntp_server=ntp.web.example.org
proxy=proxy.web.example.org
[apps]
app01.example.org
app02.example.org
[webapp:children...

Repeating tasks with loops

Oftentimes, we will want to perform a single task but use it to iterate over a set of data. Perhaps you are creating new 15 new user groups on a server for various teams to utilize. It would be incredibly inefficient to have to write 15 individual tasks within an Ansible play to achieve this – and Ansible is all about efficiency and saving the user time. To enable this level of efficiency, Ansible supports looping over datasets to ensure that you can perform large-scale operations using tightly defined code. In this section, we will explore how to make practical use of loops in your Ansible playbooks.

As ever, we must start with an inventory to work against, and we will use our by-now familiar inventory, which we have consistently used throughout this chapter:

[frontends]
web01.example.org https_port=8443
web02.example.org http_proxy=proxy.example.org
[frontends:vars]
ntp_server=ntp.web.example.org
proxy=proxy.web.example.org
[apps]
app01.example...

Grouping tasks using blocks

Blocks in Ansible allow you to logically group a set of tasks together, primarily for one of two purposes. One might be to apply conditional logic to an entire set of tasks; in this example, you could apply an identical when clause to each of the tasks, but this is cumbersome and inefficient – it’s far better to place all of the tasks in a block and apply the conditional logic to the block itself. In this way, the logic only needs to be declared once. Blocks are also valuable when it comes to error handling and especially when it comes to recovering from an error condition. We shall explore both of these through simple practical examples in this chapter to get you up to speed with blocks in Ansible.

As ever, let’s ensure we have an inventory to work from:

[frontends]
web01.example.org https_port=8443
web02.example.org http_proxy=proxy.example.org
[frontends:vars]
ntp_server=ntp.web.example.org
proxy=proxy.web.example.org
[apps...

Configuring play execution via strategies

As your playbooks become increasingly complex, it becomes more and more important that you have robust ways to debug any issues that might arise. For example, is there a way you can check the contents of a given variable (or variables) during execution without the need to insert ansible.builtin.debug statements throughout your playbook? Similarly, we have so far seen that Ansible will ensure that a particular task runs to completion on all inventory hosts that it applies to before moving on to the next task – is there a way to vary this?

When you get started with Ansible, the execution strategy that you see by default (and we have seen this so far in every playbook we have executed, even though we have not mentioned it by name) is known as linear. This does exactly what it describes – each task is executed in turn on all applicable hosts before the next task is started. However, there is another less commonly used strategy...

Using ansible-pull

Of course, the ideal way to work with Ansible code is to store it in a version control repository. This is a valuable step that ensures all changes are tracked, and that everyone responsible for automation is working from the same code. However, it also presents an inefficiency – end users must remember to check out (or pull) the latest version of the code and then execute it, and while this isn’t difficult, manual tasks are both the enemy of efficiency and make it easy for errors to occur. Luckily, once again, Ansible supports us by providing tooling to ensure the most efficient approach can be achieved, and a special command called ansible-pull can be used to both retrieve the latest code from a Git repository and execute it, all using one command. This supports not only greater efficiency for end users (and reduces the chance of human error) but also enables automation jobs to be run unattended (for example, using a scheduler such as cron).

An...

Summary

Playbooks are the lifeblood of Ansible automation, providing a robust framework within which to define logical collections of tasks and handle error conditions cleanly and robustly. The addition of roles into this mix is valuable in terms of not only organizing your code but also in terms of supporting code reuse as your automation requirements grow. Ansible playbooks provide a truly complete automation solution for your technology needs.

In this chapter, you learned about the playbook framework and how to start building your own playbooks. You then learned how to organize your code into roles and design your code to effectively and efficiently support reuse. We then explored some of the more advanced playbook writing topics, such as working with conditional logic, blocks, and loops. Finally, we looked at playbook execution strategies, especially with a view to being able to debug our playbooks effectively, and we wrapped up with a look at how we can run Ansible playbooks...

Questions

  1. How do you restart the Apache web server in the frontends host group via an ad hoc command?
    1. ansible frontends -i hosts -a "name=httpd state=restarted"
    2. ansible frontends -i hosts -b ansible.builtin.service -a "name=httpd state=restarted"
    3. ansible frontends -i hosts -b -m ansible.builtin.service -a "name=httpd state=restarted"
    4. ansible frontends -i hosts -b -m ansible.builtin.server -a "name=httpd state=restarted"
    5. ansible frontends -i hosts -m restart -a "name=httpd"
  2. Blocks allow you to logically make a group of tasks or perform error handling:
    1. True
    2. False
  3. Default strategies are implemented via the relevant modules in the playbook:
    1. True
    2. False

Further reading

ansible-galaxy and its documentation can be found here: https://galaxy.ansible.com/docs/.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Practical Ansible - Second Edition
Published in: Sep 2023 Publisher: Packt ISBN-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.
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}