Practical Ansible - James Freeman - E-Book

Practical Ansible E-Book

James Freeman

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Ansible empowers you to automate a myriad of tasks, including software provisioning, configuration management, infrastructure deployment, and application rollouts. It can be used as a deployment tool as well as an orchestration tool. While Ansible provides simple yet powerful features to automate multi-layer environments using agentless communication, it can also solve other critical IT challenges, such as ensuring continuous integration and continuous deployment (CI/CD) with zero downtime.

In this book, you'll work with the latest release of Ansible and learn how to solve complex issues quickly with the help of task-oriented scenarios. You'll start by installing and configuring Ansible on Linux and macOS to automate monotonous and repetitive IT tasks and learn concepts such as playbooks, inventories, and roles. As you progress, you'll gain insight into the YAML syntax and learn how to port between Ansible versions. Additionally, you'll understand how Ansible enables you to orchestrate multi-layer environments such as networks, containers, and the cloud.

By the end of this Ansible book, you'll be well versed in writing playbooks and other related Ansible code to overcome all your IT challenges, from infrastructure-as-a-code provisioning to application deployments and handling mundane day-to-day maintenance tasks.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 524

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Practical Ansible

Learn how to automate infrastructure, manage configuration, and deploy applications

James Freeman Fabio Alessandro Locati Daniel Oh

BIRMINGHAM—MUMBAI

Practical Ansible

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Preet Ahuja

Publishing Product Manager: Preet Ahuja

Book Project Managers: Aryaa Joshi & Ashwini Gowda

Senior Editor: Romy Dias

Technical Editor: Rajat Sharma

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Hemangini Bari

Production Designer: Joshua Misquitta

DevRel Marketing Coordinator: Rohan Dhobal

First published: June 2020

Second edition: September 2023

Production reference: 1300823

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-80512-997-4

www.packtpub.com

In memory of my grandfather Ray, who always demonstrated the power of calm and joy in situations where many would succumb to stress.

– James Freeman

To everyone that sees automation and simplification as something to pursue.

– Fabio Alessandro Locati

To my son, Justin, and daughter, Jennie, for their continued support, patience, and encouragement throughout the long process of writing this book.

– Daniel Oh

Contributors

About the authors

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.

I would like to thank Raminta Rimkute and Nicki Chartrand for their constant belief and support, for seeing something in me, and for believing that I’m capable of more than I ever thought possible.

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.

I would like to thank the many people that, during my life, have motivated me to learn more, and that helped me in the process of writing this book.

Daniel Oh is a Java Champion and senior principal developer advocate at Red Hat. He works to evangelize building cloud-native microservices and serverless functions with cloud-native runtimes to developers. He also continues to contribute to various open source cloud projects and ecosystems as a Cloud Native Computing Foundation (CNCF) ambassador to accelerate hybrid cloud platform adoption in a variety of enterprises. Daniel also speaks at technical seminars, workshops, and meetups to elaborate on new emerging technologies for enterprise developers, SREs, platform engineers, and DevOps teams.

I would like to first and foremost thank my loving and patient wife and kids for their continued support, patience, and encouragement throughout the long process of writing this book. Thanks also to the subject-matter experts (SMEs) in the Ansible community project for their continuous contribution with their practical code – obviously critical references for this book.

About the reviewers

Werner Dijkerman is a freelance-platform, Kubernetes (certified), and Dev(Sec)Ops engineer. He’s currently focused on, and working with, cloud-native solutions and tools, including AWS, Ansible, Kubernetes, and Terraform. He also focuses on infrastructure as code and monitoring the correct “thing,” with tools such as Zabbix, Prometheus, and the ELK stack. He has a passion for automating everything and avoiding doing anything that resembles manual work. He is an active reader of comics, self-care/psychology, and IT-related books, where he is a technical reviewer of various books about DevOps, CI/CD, and Kubernetes.

Rewanth Tammana is a security ninja, open source contributor, AWS community builder, and full-time freelancer. Previously, he was a senior security architect at the National Bank of Dubai. He is passionate about DevSecOps, the cloud, and container security, and he has contributed over 17,000 lines of code to Nmap and holds industry certifications such as CKS and CKA.

Rewanth presents at security conferences such as Black Hat, DEF CON, HITB, CRESTCon, and PHDays. Rewanth was recognized as a Bugcrowd MVP researcher in 2018, having identified vulnerabilities in various organizations. He has published an IEEE research paper on an offensive attack in machine learning and security, and he was selected for the prestigious Google Summer of Code.

Table of Contents

Preface

Part 1:Learning the Fundamentals of Ansible

1

Getting Started with Ansible

Technical requirements

Installing and configuring Ansible

Understanding Ansible version numbers

Installing Ansible on Linux and FreeBSD

Working with virtual environments

Installing from GitHub

Installing Ansible on macOS

Configuring Windows hosts for Ansible

Getting to know your Ansible installation

Understanding how Ansible connects to hosts

Verifying the Ansible installation

Managed node requirements

Summary

Questions

Further reading

2

Understanding the Fundamentals of Ansible

Technical requirements

Getting familiar with the Ansible framework

Breaking down the Ansible components

Learning the YAML syntax

Organizing your automation code

Exploring the configuration file

Command-line arguments

Understanding ad hoc commands

Defining variables

Understanding Jinja2 filters

Summary

Questions

Further reading

3

Defining Your Inventory

Technical requirements

Creating an inventory file and adding hosts

Using host groups

Adding host and group variables to your inventory

Generating a dynamic inventory file

Using multiple inventory sources in the inventory directories

Using static groups with dynamic groups

Special host management using patterns

Summary

Questions

Further reading

4

Playbooks and Roles

Technical requirements

Understanding the playbook framework

Comparing playbooks and ad hoc tasks

Defining plays and tasks

Understanding roles – the playbook organizer

Setting up role-based variables and dependencies

Ansible Galaxy

Using conditions in your code

Repeating tasks with loops

Grouping tasks using blocks

Configuring play execution via strategies

Using ansible-pull

Summary

Questions

Further reading

Part 2:Expanding the Capabilities of Ansible

5

Creating and Consuming Modules

Technical requirements

Executing multiple modules using the command line

Reviewing the module index

Accessing module documentation from the command line

Module return values

Developing custom modules

Avoiding common pitfalls

Testing and documenting your module

The module checklist

Contributing upstream – submitting a GitHub pull request

Summary

Questions

Further reading

6

Creating and Consuming Collections

Technical requirements

Introduction to Ansible collections

Understanding fully qualified collection names

Managing collections on your control node

Updating your Ansible collections and core installation

Creating your own collections

Summary

Questions

Further reading

7

Creating and Consuming Plugins

Technical requirements

Discovering the plugin types

Finding included plugins

Creating custom plugins

Learning to integrate custom plugins with Ansible source code

Sharing plugins with the community

Summary

Questions

Further reading

8

Coding Best Practices

Technical requirements

The preferred directory layout

Differentiating between different environment types

The proper approach to defining group and host variables

Using top-level playbooks

Leveraging version control tools

Setting OS and distribution variances

Porting between Ansible versions

Summary

Questions

Further reading

9

Advanced Ansible Topics

Technical requirements

Asynchronous versus synchronous actions

Controlling play execution for rolling updates

Configuring the maximum failure percentage

Setting task execution delegation

Using the run_once option

Running playbooks locally

Working with proxies and jump hosts

Configuring playbook prompts

Placing tags in the plays and tasks

Securing data with Ansible Vault

Summary

Questions

Further reading

Part 3:Using Ansible in an Enterprise

10

Network Automation with Ansible

Technical requirements

Why automate network management?

How Ansible manages networking devices

How to enable network automation

The available Ansible networking modules

Connecting to network devices

Environment variables for network devices

Custom conditional statements for networking devices

Summary

Questions

Further reading

11

Container and Cloud Management

Technical requirements

Automating Docker and Podman with Ansible

Managing Docker

Managing Podman

Managing Kubernetes with Ansible

Installing Ansible Kubernetes dependencies

Listing Kubernetes namespaces with Ansible

Creating a Kubernetes namespace with Ansible

Creating a Kubernetes service with Ansible

Exploring container-focused modules

Automating with Amazon Web Services

Installation

Authentication

Creating your first machine

Complementing Google Cloud Platform with automation

Installation

Authentication

Creating your first machine

Seamless automation integration with Azure

Installation

Authentication

Creating your first machine

Using Ansible to orchestrate OpenStack

Installation

Authentication

Creating your first machine

Summary

Questions

Further reading

12

Troubleshooting and Testing Strategies

Technical requirements

Digging into playbook execution problems

Using host facts to diagnose failures

Testing with a playbook

Using check mode

Solving host connection issues

Passing working variables via the CLI

Limiting the host’s execution

Flushing the code cache

Checking for bad syntax

Summary

Questions

Further reading

13

Getting Started with Ansible Automation Controller

Technical requirements

Installing AWX

Running your first playbook from AWX

Creating an AWX project

Creating an inventory

Creating a job template

Running a job

Controlling access to AWX

Creating a user

Creating a team

Creating an organization

Assigning permissions in AWX

Summary

Questions

14

Execution Environments

Technical requirements

The importance of execution environments

Building an execution environment

Creating a minimal execution environment

Creating an execution environment with a specific Python interpreter

Creating an execution environment with additional dependencies

Running playbooks in an execution environment

Uploading execution environments to a container registry

Using execution environments in Ansible Automation Controller

Summary

Questions

Further reading

Assessments

Chapter 1

Chapter 2

Chapter 3

Chapter 4

Chapter 5

Chapter 6

Chapter 7

Chapter 8

Chapter 9

Chapter 10

Chapter 11

Chapter 12

Chapter 13

Chapter 14

Index

Other Books You May Enjoy

Preface

Welcome to Practical Ansible – Second Edition, your guide to going from being a beginner to a proficient Ansible automation engineer in the space of a few chapters. This book will provide you with the knowledge and skills required to perform your very first installation and automation tasks with Ansible and take you on a journey from simple one-line automation commands that perform single tasks all the way through to writing your own complex custom code to extend the functionality of Ansible, and even automate cloud and container infrastructures. Throughout the book, practical examples will be given for you to not just read about Ansible automation but also actually try it out for yourself and understand how the code works. You will then be well placed to automate your infrastructure with Ansible in a manner that is scalable, repeatable, and reliable.

Who this book is for

This book is for anyone who has IT tasks they want to automate, from mundane day-to-day housekeeping tasks to complex infrastructure-as-code-based deployments. It is intended to appeal to anyone with prior experience with Linux-based environments who wants to get up to speed quickly with Ansible automation and to a wide range of individuals, whether system administrators, DevOps engineers, or architects looking at overall automation strategy. It will even serve hobbyists well. Basic proficiency in Linux system administration and maintenance tasks is assumed; however, no previous Ansible or automation experience is required.

What this book covers

Chapter 1, Getting Started with Ansible, provides the steps you need for your very first installation of Ansible, and explains how to get up and running with this powerful form of automation.

Chapter 2, Understanding the Fundamentals of Ansible, explores the Ansible framework, gives you a sound understanding of the fundamentals of the Ansible language, and explains how to work with the various command-line tools that it comprises.

Chapter 3, Defining Your Inventory, gives you details about the Ansible inventory, its purpose, and how to create your own inventories and work with them. It also explores the differences between static and dynamic inventories, and when to leverage each type.

Chapter 4, Playbooks and Roles, provides you with an in-depth look at creating your own automation code in Ansible in the form of playbooks, and how to enable effective reuse of that code through roles.

Chapter 5, Creating and Consuming Modules, teaches you about Ansible modules and their purpose, and then provides you with the steps required to write your own module, and even to submit it to the Ansible project for inclusion.

Chapter 6, Creating and Consuming Collections, explores Ansible Collections, covering their design, intention, and why they are essential to the future of Ansible. We then proceed to guide you through the creation and consumption of your own collection to give you first-hand experience.

Chapter 7, Creating and Consuming Plugins, explains the purpose of Ansible plugins, and covers the various types of plugins that Ansible uses. It then explains how to write your own plugins, and explains how to submit your code to the Ansible project.

Chapter 8, Coding Best Practices, provides an in-depth look at the best practices that you should adhere to while writing Ansible automation code to ensure that your solutions are manageable, easy to maintain, and easy to scale.

Chapter 9, Advanced Ansible Topics, explores some of the more advanced Ansible options and language directives, which are valuable in a scenario such as performing a roll-out to a highly available cluster. It also explains how to work with jump hosts to automate tasks on secure networks, and how to encrypt your variable data at rest.

Chapter 10, Network Automation with Ansible, provides a detailed look at the importance of network automation, explains why Ansible is especially well suited to this task, and takes you through practical examples of how to connect to a variety of network devices with Ansible.

Chapter 11, Container and Cloud Management, explores the manner in which Ansible supports working with both cloud and container platforms and teaches you how to build containers with Ansible, along with methods to deploy infrastructure as code in a cloud environment using Ansible.

Chapter 12, Troubleshooting and Testing Strategies, teaches you how to test and debug your Ansible code, and gives you robust strategies to handle errors and unexpected failures both with playbooks and the agentless connections on which Ansible relies.

Chapter 13, Getting Started with Ansible Automation Controller, provides an introduction to Ansible Automation Controller and its upstream open source counterpart, AWX, demonstrating how this powerful tool provides a valuable complement to Ansible, especially in large, multi-user environments such as enterprises.

Chapter 14, Execution Environment, provides an introduction to Execution Environments, demonstrating how to create them, how to share them, and how to use them both on the command line and within Ansible Automation Controller.

To get the most out of this book

All the chapters of this book assume you have access to at least one Linux machine running a relatively recent Linux distribution. All examples in this book were tested on Fedora 38 and Ubuntu Server 22.04, but should work on just about any other mainstream distribution. You will require Ansible 2.15 installed on at least one test machine too – the installation steps will be covered in the very first chapter. Later versions of Ansible should also work, though there may be some subtle differences, and you should refer to the release notes and porting guide for newer Ansible versions. The final two chapters also take you through the installation of AWX, but this assumes a Linux server with Ansible installed. Most of the examples demonstrate automation across more than one host, and, if you have more Linux hosts available, you will be able to get more out of the examples; however, they can be scaled up or down as you require. Having more hosts is not mandatory, but enables you to get more out of the book.

Software/hardware covered in the book

Operating system requirements

At least one Linux server (a virtual or physical machine).

Fedora 38 or Ubuntu Server 22.04, though other mainstream distributions (including newer versions of these operating systems) should work.

Ansible 8.0

As above.

AWX release 22.4.0 or later

As above.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Practical-Ansible-Second-Edition. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The first is called ansible-core, and this contains the Ansible runtime code (such as the ansible-playbook command, which we'll see in use later), as well as some built-in functionality that is core to all playbooks and roles.”

A block of code is set as follows:

  tasks:   - name: Install/Update to the latest of Apache Web Server     ansible.builtin.apt:       name: apache2       state: latest

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

  handlers:   - name: Restart the Apache Web Server     ansible.builtin.service:       name: apache2       state: restarted

Any command-line input or output is written as follows:

$ python3 --version Python 3.10.6

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select System info from the Administration panel.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share your thoughts

Once you’ve read Practical Ansible - Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781805129974

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1:Learning the Fundamentals of Ansible

In this section, we will take a look at the very fundamentals of Ansible. We will start with the process of installing Ansible and then we will get to grips with the fundamentals, including the basics of the language and ad-hoc commands. We will then explore Ansible inventories, before looking at writing our very first playbooks and roles to complete multi-stage automation tasks.

This section contains the following chapters:

Chapter 1, Getting Started with AnsibleChapter 2, Understanding the Fundamentals of AnsibleChapter 3, Defining Your InventoryChapter 4, Playbooks and Roles