36,59 €
Take your network automation skills to the next level with practical recipes on managing network devices from a variety of vendors like Cisco, Juniper, and Arista
Key Features
Book Description
Network Automation Cookbook is designed to help system administrators, network engineers, and infrastructure automation engineers to centrally manage switches, routers, and other devices in their organization's network. This book will help you gain hands-on experience in automating enterprise networks and take you through core network automation techniques using the latest version of Ansible and Python.
With the help of practical recipes, you'll learn how to build a network infrastructure that can be easily managed and updated as it scales through a large number of devices. You'll also cover topics related to security automation and get to grips with essential techniques to maintain network robustness. As you make progress, the book will show you how to automate networks on public cloud providers such as AWS, Google Cloud Platform, and Azure. Finally, you will get up and running with Ansible 2.9 and discover troubleshooting techniques and network automation best practices.
By the end of this book, you'll be able to use Ansible to automate modern network devices and integrate third-party tools such as NAPALM, NetBox, and Batfish easily to build robust network automation solutions.
What you will learn
Who this book is for
This Ansible network automation book is for network and DevOps engineers interested in automating complex network tasks. Prior understanding of networking and basic Linux knowledge is required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 422
Veröffentlichungsjahr: 2020
Copyright © 2020 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 author, 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.
Commissioning Editor: Vijin BorichaAcquisition Editor:Rohit RajkumarContent Development Editor: Ronn KurienSenior Editor: Richard Brookes-BlandTechnical Editor: Dinesh PawarCopy Editor: Safis EditingProject Coordinator:Neil DmelloProofreader: Safis EditingIndexer:Tejal Daruwale SoniProduction Designer:Nilesh Mohite
First published: April 2020
Production reference: 1170420
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78995-648-1
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Karim Okasha is a network consultant with over 15 years of experience in the ICT industry. He is specialized in the design and operation of large telecom and service provider networks and has lots of experience in network automation. Karim has a bachelor's degree in telecommunications and holds several expert-level certifications, such as CCIE, JNCIE, and RHCE. He is currently working in Red Hat as a network automation consultant, helping large telecom and service providers to design and implement innovative network automation solutions. Prior to joining Red Hat, he worked for Saudi Telecom Company as well as Cisco and Orange S.A.
Mohamed Radwan is a senior network architect with 20 years of experience in designing solutions for telecommunications, global service providers, data centers, the cloud, governments, and Fortune 500 companies in Europe, the Middle East, and the Asia-Pacific. He is the author of CCDE: The Practical Guide, he is an award-winning network designer, and he holds bachelor's degree in engineering – computers and systems, in addition to many expert-level certificates. He currently lives in Sydney, Australia, working within the Cisco Advanced Services team. Before that, he worked with Orange S.A, Saudi Telecom Company, Qatar Foundation, and Vodafone.
Bassem Aly is a senior SDN/NFV solution consultant at Juniper Networks and has been working in the telecom industry for the last 10 years. He is focused on designing and implementing next-generation networks by leveraging different automation and DevOps frameworks. Also, he has extensive experience in architecting and deploying telecom applications over OpenStack. Bassem also conducts corporate training on network automation and network programmability using Python and Ansible. Finally, he's an active blogger on different technology areas and is the author of Hands-On Enterprise Automation with Python, published by Packt.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Network Automation Cookbook
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in Action
Conventions used
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Get in touch
Reviews
Building Blocks of Ansible
Technical requirements
Installing Ansible
Getting ready
How to do it...
How it works..
How it works...
See also...
Building Ansible's inventory
Getting ready
How to do it...
How it works...
Using Ansible's variables
Getting ready
How to do it...
How it works...
There's more...
Building Ansible's playbook
Getting ready
How to do it...
How it works...
Using Ansible's conditionals
Getting ready
How to do it...
How it works...
See also...
Using Ansible's loops
Getting ready
How to do it...
How it works..
See also...
Securing secrets with Ansible Vault
How to do it...
How it works..
There's more...
Using Jinja2 with Ansible
Getting ready
How to do it...
How it works...
See also...
Using Ansible's filters
How to do it...
How it works...
Using Ansible Tags
How to do it...
How it works...
See also...
Customizing Ansible's settings
How to do it...
How it works...
See also...
Using Ansible Roles
How to do it...
How it works...
See also
Managing Cisco IOS Devices Using Ansible
Technical requirements
Building an Ansible network inventory
Getting ready
How to do it...
How it works...
Connecting to Cisco IOS devices
Getting ready
How to do it...
How it works...
There's more...
Configuring basic system information
Getting ready
How to do it...
How it works...
See also...
Configuring interfaces on IOS devices
Getting ready
How to do it...
How it works...
See also...
Configuring L2 VLANs on IOS devices
Getting ready
How to do it...
How it works...
Configuring trunk and access interfaces
Getting ready 
How to do it...
How it works...
See also...
Configuring interface IP addresses
Getting ready
How to do it...
How it works...
See also...
Configuring OSPF on IOS devices
Getting ready
How to do it...
How it works...
Collecting IOS device facts
Getting ready
How to do it...
How it works...
There's more...
See also...
Validating network reachability on IOS devices
Getting ready
How to do it...
How it works...
Retrieving operational data from IOS devices
Getting ready
How to do it...
How it works...
Validating network states with pyATS and Ansible
Getting ready
How to do it...
How it works...
See also...
Automating Juniper Devices in the Service Providers Using Ansible
Technical requirements
Building the network inventory
Getting ready
How to do it...
How it works...
Connecting and authenticating to Juniper devices
Getting ready
How to do it...
How it works...
There's more...
Enabling NETCONF on Junos OS devices
Getting ready
How to do it...
How it works...
Configuring generic system options on Juniper devices
Getting ready
How to do it...
How it works...
There's more...
See also...
Configuring interfaces on Juniper devices
Getting ready
How to do it...
How it works...
There's more...
Configuring OSPF on Juniper devices
How to do it...
How it works...
Configuring MPLS on Juniper devices
How to do it...
How it works...
Configuring BGP on Juniper devices
How to do it...
How it works...
Deploying configuration on Juniper devices
Getting ready
How to do it...
How it works...
There's more...
See also...
Configuring the L3VPN service on Juniper devices
Getting ready
How to do it...
How it works...
See also...
Gathering Juniper device facts using Ansible
Getting ready
How to do it...
How it works...
See also...
Validating network reachability on Juniper devices
Getting ready
How to do it...
How it works...
See also...
Retrieving operational data from Juniper devices
Getting ready
How to do it...
How it works...
There's more...
Validating the network state using PyEZ operational tables
Getting ready
How to do it...
How it works...
See also...
Building Data Center Networks with Arista and Ansible
Technical requirements
Building the Ansible network inventory
Getting ready
How to do it...
How it works...
Connecting to and authenticating Arista devices from Ansible
Getting ready
How to do it...
How it works...
Enabling eAPI on Arista devices
Getting ready
How to do it...
How it works...
See also...
Configuring generic system options on Arista devices
Getting ready
How to do it...
How it works...
There's more...
Configuring interfaces on Arista devices
Getting ready
How to do it...
How it works...
There's more...
See also...
Configuring the underlay BGP on Arista devices
Getting ready
How to do it...
How it works...
Configuring the overlay BGP EVPN on Arista devices
Getting ready
How to do it...
How it works...
Deploying the configuration on Arista devices
Getting ready
How to do it...
How it works...
See also...
Configuring VLANs on Arista devices
Getting ready
How to do it...
How it works...
See also...
Configuring VXLANs tunnels on Arista devices
Getting ready
How to do it...
How it works...
Gathering Arista device facts
Getting ready
How to do it...
How it works...
See also...
Retrieving operational data from Arista devices
Getting ready
How to do it...
How it works...
See also...
Automating Application Delivery with F5 LTM and Ansible
Technical requirements
Building an Ansible network inventory
Getting ready
How to do it...
How it works...
Connecting and authenticating to BIG-IP devices
Getting ready
How to do it...
How it works...
There's more...
Configuring generic system options on BIG-IP devices
Getting ready
How to do it...
How it works...
Configuring interfaces and trunks on BIG-IP devices
Getting ready
How to do it...
How it works...
See also...
Configuring VLANs and self-IPs on BIG-IP devices
Getting ready
How to do it...
How it works...
See also...
Configuring static routes on BIG-IP devices
Getting ready
How to do it...
How it works...
Deploying nodes on BIG-IP devices
Getting ready
How to do it...
How it works...
Configuring a load balancing pool on BIG-IP devices
Getting ready
How to do it...
How it works...
See also...
Configuring virtual servers on BIG-IP devices
Getting ready
How to do it...
How it works...
See also...
Retrieving operational data from BIG-IP nodes
Getting ready
How to do it...
How it works...
There's more...
See also...
Administering a Multi-Vendor Network with NAPALM and Ansible
Technical requirements
Installing NAPALM and integrating with Ansible
Getting ready
How to do it...
How it works…
Building an Ansible network inventory
How to do it…
How it works…
Connecting and authenticating to network devices using Ansible
Getting ready
How to do it…
How it works…
Building the device configuration
Getting ready
How to do it…
How it works…
Deploying configuration on network devices using NAPALM
Getting ready
How to do it…
How it works…
There's more…
Collecting device facts with NAPALM
Getting ready
How to do it…
How it works…
See also…
Validating network reachability using NAPALM
Getting ready
How to do it…
How it works…
Validating and auditing networks with NAPALM
Getting ready
How to do it…
How it works…
See also…
Deploying and Operating AWS Networking Resources with Ansible
Technical requirements
Installing the AWS SDK
Getting ready
How to do it...
How it works...
Building an Ansible inventory
How to do it...
How it works...
Authenticating to your AWS account
Getting ready
How to do it...
How it works...
Deploying VPCs using Ansible
Getting ready
How to do it...
How it works...
See also
Deploying subnets using Ansible
Getting ready
How to do it...
How it works...
See also
Deploying IGWs using Ansible
Getting ready
How to do it...
How it works...
See also
Controlling routing within a VPC using Ansible
Getting ready
How to do it...
How it works...
See also
Deploying network ACLs using Ansible
Getting ready
How to do it...
How it works...
See also
Deployment validation using Ansible
Getting ready
How to do it...
How it works...
See also
Decommissioning resources on AWS using Ansible
Getting ready
How to do it...
How it works...
Deploying and Operating Azure Networking Resources with Ansible
Technical requirements
Installing the Azure SDK
Getting ready
How to do it…
How it works…
See also…
Building an Ansible inventory
How to do it…
How it works…
Authenticating to your Azure account
Getting ready
How to do it…
How it works…
See also…
Creating a resource group
Getting ready
How to do it…
How it works...
See also...
Creating virtual networks
Getting ready
How to do it...
How it works...
See also...
Creating subnets
Getting ready
How to do it...
How it works...
See also...
Building user-defined routes
Getting ready
How to do it...
How it works...
See also...
Deploying network security groups
Getting ready
How to do it...
How it works...
See also...
Deployment validation using Ansible
Getting ready
How to do it...
How it works...
See also...
Decommissioning Azure resources using Ansible
Getting ready
How to do it...
How it works...
Deploying and Operating GCP Networking Resources with Ansible
Technical requirements
Installing the GCP SDK
Getting ready
How to do it...
How it works...
See also...
Building an Ansible inventory
How to do it...
How it works...
Authenticating to your GCP account
Getting ready
How to do it...
How it works...
There's more...
See also...
Creating GCP VPC networks
Getting ready
How to do it...
How it works...
There is more...
See also...
Creating subnets
Getting ready
How to do it...
How it works...
See also...
Deploying firewall rules in GCP
Getting ready
How to do it...
How it works...
See also...
Deploying VMs in GCP
Getting ready
How to do it...
How it works...
See also...
Adjusting routing within a VPC
Getting ready
How to do it...
How it works..
See also...
Validating GCP deployment using Ansible
Getting ready
How to do it...
How it works...
See also...
Decommissioning GCP resources using Ansible
Getting ready
How to do it...
How it works...
Network Validation with Batfish and Ansible
Technical requirements
Installing Batfish
Getting ready
How to do it...
How it works…
See also...
Integrating Batfish with Ansible
Getting ready
How to do it…
How it works…
See also...
Generating the network configuration
Getting ready
How to do it...
How it works...
Creating a network snapshot for Batfish
Getting ready
How to do it...
How it works…
See also...
Initializing the network snapshot with Ansible
Getting ready
How to do it...
How it works...
Collecting network facts from Batfish
Getting ready
How to do it...
How it works...
There's more...
See also...
Validating traffic forwarding with Batfish
Getting ready
How to do it...
How it works...
Validating ACLs with Batfish
Getting ready
How to do it…
How it works…
Building a Network Inventory with Ansible and NetBox
Technical requirements
Installing NetBox
Getting ready
How to do it…
How it works…
There's more
See also...
Integrating NetBox with Ansible
Getting ready
How to do it…
How it works…
See also...
Populating sites in NetBox
Getting ready
How to do it…
How it works…
See also...
Populating devices in NetBox
Getting ready
How to do it...
How it works…
See also...
Populating interfaces in NetBox
Getting ready
How to do it…
How it works…
See also...
Populating IP addresses in NetBox
Getting ready
How to do it…
How it works…
See also...
Populating IP prefixes in NetBox
Getting ready
How to do it…
How it works…
See also...
Using NetBox as a dynamic inventory source for Ansible
Getting ready
How to do it…
How it works…
There's more
See also...
Generating a configuration using NetBox
Getting ready
How to do it…
How it works…
Simplifying Automation with AWX and Ansible
Technical requirements
Installing AWX
Getting ready
How to do it…
How it works…
There's more...
See also...
Managing users and teams on AWX
Getting ready
How to do it…
How it works…
See also...
Creating a network inventory on AWX
Getting ready
How to do it…
How it works…
Managing network credentials on AWX
Getting ready
How to do it…
How it works…
See also...
Creating projects on AWX
Getting ready
How to do it…
How it works…
See also...
Creating templates on AWX
Getting ready
How to do it…
How it works…
See also...
Creating workflow templates on AWX
Getting ready
How to do it…
How it works…
See also...
Running automation tasks using the AWX API
Getting ready
How to do it…
How it works…
There's more…
See also...
Advanced Techniques and Best Practices for Ansible
Technical requirements
Installing Ansible in a virtual environment
Getting ready
How to do it...
How it works...
Validating YAML and Ansible playbooks
Getting ready
How to do it...
How it works...
There's more...
See also...
Calculating the execution time for Ansible playbooks
How to do it...
How it works...
See also...
Validating user input using Ansible
How to do it...
How it works...
Running Ansible in check mode
How to do it...
How it works...
There's more...
See also...
Controlling parallelism and rolling updates in Ansible
How to do it...
How it works...
See also...
Configuring fact caching in Ansible
How to do it...
How it works...
There's more...
See also...
Creating custom Python filters for Ansible
How to do it...
How it works...
There's more...
Other Books You May Enjoy
Leave a review - let other readers know what you think
Network Automation Cookbook provides an overview of the various topics of network automation and how to use software development practices in order to design and operate different networking solutions. We use Ansible as our framework to introduce the topic of network automation and how to manage different vendor equipment using Ansible. In the first section, we outline how to install and configure Ansible specifically for the purpose of network automation. We will explore how we can use Ansible to manage traditional network solutions from various vendors such as Cisco, Juniper, Arista, and F5. Next, we continue to explore how to utilize Ansible to build and scale network solutions from major cloud providers such as AWS, Azure, and Google Cloud Platform (GCP). Finally, we outline different supporting open source projects in network automation, such as NetBox, Batfish, and AWX. We outline how to integrate all these tools with Ansible in order to build a complete framework for network automation.
By the end of this book, you will have a solid foundation on how to integrate Ansible with different vendor equipment and how to build a network automation solution based on Ansible. Further, you will understand how to use various open source projects and how to integrate all these solutions with Ansible to build a robust and scalable network automation framework.
This book is ideal for IT professionals and network engineers who are responsible for the design and operation of network devices within an organization and would like to expand their knowledge on using Ansible to automate their network infrastructure. Basic knowledge of networking and Linux is recommended.
Chapter 1, Building Blocks of Ansible, focuses on how to install Ansible and describes the main building blocks of Ansible and how to utilize them to build advanced Ansible playbooks.
Chapter 2, Managing Cisco IOS Devices Using Ansible, focuses on how to integrate Ansible with Cisco IOS devices and how to use Ansible to configure Cisco IOS devices. We will explore the core Ansible modules developed to interact with Cisco IOS devices. Finally, we will explore how to use the Cisco PyATS library and how to integrate it with Ansible in order to validate the network state on Cisco IOS and Cisco IOS-XE devices.
Chapter 3, Automating Juniper Devices in the Service Providers Using Ansible, describes how to integrate Ansible with Juniper devices in Service Provider (SP) environments and how to manage the configuration of Juniper devices using Ansible. We will explore how to use the core Ansible modules developed to manage Juniper devices. Furthermore, we will explore the PyEZ library, which is used by Juniper custom Ansible modules to extend Ansible functionality in managing Juniper devices.
Chapter 4, Building Data Center Networks with Arista and Ansible, outlines how to integrate Ansible with Arista devices to build data center fabrics using EVPN/VXLANs. We will explore how to use the core Ansible modules developed to manage Arista devices and how to use these modules to configure and validate the network state on Arista switches.
Chapter 5, Automating Application Delivery with F5 LTM and Ansible, focuses on how to integrate Ansible with F5 BIG-IP LTM devices to onboard new BIG-IP LTM devices and how to set up the BIG-IP system as a reverse proxy for application delivery.
Chapter 6, Administering Multi-Vendor Network with NAPALM and Ansible, introduces the NAPALM library and outlines how to integrate this library with Ansible. We will explore how to utilize Ansible and NAPALM to simplify the management of multi-vendor environments.
Chapter 7, Deploying and Operating AWS Networking Resources with Ansible, outlines how to integrate Ansible with your AWS environment and how to describe your AWS infrastructure using Ansible. We explore how to utilize the core Ansible AWS modules to manage networking resources in AWS in order to build your AWS network infrastructure using Ansible.
Chapter 8, Deploying and Operating Azure Networking Resources with Ansible, outlines how to integrate Ansible with your Azure environment and how to describe your Azure infrastructure using Ansible. We will explore how to utilize the core Ansible Azure modules to manage networking resources in Azure in order to build Azure network solutions using Ansible.
Chapter 9, Deploying and Operating GCP Networking Resources with Ansible, describes how to integrate Ansible with your GCP environment and how to describe your GCP infrastructure using Ansible. We explore how to utilize the core Ansible GCP modules to manage networking resources in GCP in order to build GCP network solutions using Ansible.
Chapter 10, Network Validation with Batfish and Ansible, introduces the Batfish framework for offline network validation and how to integrate this framework with Ansible in order to perform offline network validation using both Ansible and Batfish.
Chapter 11, Building a Network Inventory with Ansible and NetBox, introduces NetBox, which is a complete inventory system to document and describe any network. We outline how to integrate Ansible with NetBox and how to use NetBox data to build Ansible dynamic inventories.
Chapter 12, Simplifying Automation with AWX and Ansible, introduces the AWX project, which extends Ansible and provides a powerful GUI and API on top of Ansible to simplify running automation tasks within an organization. We outline the extra features provided by AWX and how to use it to manage network automation within an organization.
Chapter 13,Advanced Techniques and Best Practices for Ansible, describes various best practices and advanced techniques that can be used for more advanced playbooks.
Basic knowledge regarding different networking concepts, such as Open Shortest Path First (OSPF) and Border Gateway Protocol (BGP), is assumed.
Basic knowledge of Linux is assumed, including knowledge of how to create files and folders and install software on Linux machines.
Software/hardware covered in the book
OS requirements
Ansible 2.9
CentOS 7
Python 3.6.8
If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Network-Automation-Cookbook. In case there's an update to the code, it will be updated on the existing 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!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781789956481_ColorImages.pdf.
The code in action videos are based on Ansible version 2.8.5. The code has also been tested on version 2.9.2 and works fine.
Visit the following link to check out videos of the code being run:https://bit.ly/34JooNp
There are a number of text conventions used throughout this book.
CodeInText: 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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
$ cat ansible.cfg
[defaults]
inventory=hosts
retry_files_enabled=False
gathering=explicit
host_key_checking=False
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
- name: Configure ACL on IOS-XR hosts: all serial: 1 tags: deploy tasks: - name: Backup Config iosxr_config: backup:
when: not ansible_check_mode
- name: Deploy ACLs iosxr_config: src: acl_conf.cfg match: line
when: not ansible_check_mode
Any command-line input or output is written as follows:
$ python3 -m venv dev
$ source dev/bin/activate
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
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, selecting your book, clicking on the Errata Submission Form link, and entering the details.
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.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Ansible is an enormously popular automation framework that has been used to automate IT operations for a long time. It simplifies the management of different infrastructure nodes and translates the business logic into well-defined procedures in order to implement this business logic. Ansible is written in Python and it mainly relies on SSH to communicate with infrastructure nodes to execute instructions on them. It started support for networking devices beginning with Ansible 1.9, and with Ansible 2.9, its current support for network devices has grown extensively. It can interact with network devices using either SSH or via API if the network vendors support APIs on their equipment. It also provides multiple advantages, including the following:
An easy learning curve:
Writing Ansible playbooks requires knowledge of YAML and Jinja2 templates, which are easy to learn, and its descriptive language is easy to understand.
Agentless:
It doesn't require an agent to be installed on the remotely managed device in order to control this device.
Extensible:
Ansible comes equipped with multiple modules to execute a variety of tasks on the managed nodes. It also supports writing custom modules and plugins to extend Ansible's core functionality.
Idempotent:
Ansible will not change the state of the device unless it needs to in order to change its setting to reach the desired state. Once it is in this desired state, running Ansible Playbooks against the device will not alter its configurations.
In this chapter, we will introduce the main components of Ansible and outline the different features and options that Ansible supports. The following are the main recipes that will be covered:
Installing Ansible
Building Ansible's inventory
Using Ansible's variables
Building Ansible's playbook
Using Ansible's conditionals
Using Ansible's loops
Securing secrets with Ansible Vault
Using Jinja2 with Ansible
Using Ansible's filters
Using Ansible Tags
Customizing Ansible's settings
Using Ansible Roles
The purpose of this chapter is to have a basic understanding of the different Ansible components that we will utilize throughout this book in order to interact with the networking device. Consequently, all the examples in this chapter are not focused on managing networking devices. Instead, we will focus on understanding the different components in Ansible in order to use them effectively in the next chapters.
Here are the requirements for installing Ansible and running all of our Ansible playbooks:
A Linux
Virtual Machine
(
VM
) with either of the following distributions:
Ubuntu 18.04 or higher
CentOS 7.0 or higher
Internet connectivity for the VM
The machine on which we install Ansible (this is known as the Ansible control machine) should be running on any Linux distribution. In this recipe, we will outline how to install Ansible on both an Ubuntu Linux machine or a CentOS machine.
To install Ansible, we need a Linux VM using either an Ubuntu 18.04+ OS or CentoS 7+ OS. Furthermore, this machine needs to have internet access for Ansible to be installed on it.
Ansible is written in Python and all its modules need Python to be installed on the Ansible control machine. Our first task is to ensure that Python is installed on the Ansible control machine, as outlined in the following steps.
Most Linux distributions have Python installed by default. However, if Python is not installed, here are the steps for installing it on Linux:
On an Ubuntu OS, execute the following command:
# Install python3
$sudo apt-get install python3
# validate python is installed
$python3 --version
Python 3.6.9
On a CentOS OS,
execute the following command:
# Install python
$sudo yum install pytho3
# validate python is installed
$python3 --version
Python 3.6.8
After we have validated that Python is installed, we can start to install Ansible:
On an Ubuntu OS,
execute the following command:
# We need to use ansible repository to install the latest version of Ansible
$
sudo apt-add-repository ppa:ansible/ansible
# Update the repo cache to use the new repo added
$
sudo apt-get update
# We install Ansible
$ sudo apt-get install ansible
On a CentOS OS,
execute the following command:
# We need to use latest epel repository to get the latest ansible
$
sudo yum install epel-release
# We install Ansible
$ sudo yum install ansible
For more information regarding the installation of Ansible, please check the following URL:
https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html
After installing Ansible, we need to define Ansible's inventory, which is a text file that defines the nodes that Ansible will manage. In this recipe, we will outline how to create and structure Ansible's inventory file.
We need to create a folder that will contain all the code that we will outline in this chapter. We create a folder called ch1_ansible, as shown here:
$ mkdir ch1_ansible
$ cd ch1_ansible
Perform the following steps to create the inventory file:
Create a file named
hosts
:
$ touch hosts
U
sing any text editor, open the file and add the following content:
$ cat hosts
[cisco]
csr1 ansible_host=172.10.1.2
csr2 ansible_host=172.10.1.3
[juniper]
mx1 ansible_host=172.20.1.2
mx2 ansible_host=172.20.1.3
[core]
mx1
mx2
[edge]
csr[1:2]
[network:children]
core
edge
The Ansible inventory files define the hosts that will be managed by Ansible (in the preceding example, this is csr1-2 and mx1-2 ) and how to group these devices into custom-defined groups based on different criteria. The groups are defined with []. This grouping helps us to define the variables and simplify the segregation between the devices and how Ansible interacts with them. How we group the devices is based on our use case, so we can group them as per the vendor (Juniper and IOS) or function (core and edge).
We can also build hierarchies for the groups using the children, which is outlined in the inventory file. The following diagram shows how the hosts are grouped and how the group hierarchy is built:
Ansible stores the information for the nodes that it manages using Ansible variables. Ansible variables can be declared in multiple locations. However, in observing the best practices for Ansible, we will outline the two main parts where Ansible looks for variables for the nodes that are declared in the inventory file.
In order to follow along with this recipe, an Ansible inventory file must be already defined as outlined in the previous recipes.
In the inventory file, we define hosts and we group the hosts into groups. We now define two directories that Ansible searches for group variables and host variables:
Create two folders,
group_vars
and
host_vars
:
$ cd ch1_ansible
$
mkdir group_vars host_vars
Create
ios.yml
and
junos.yml
files inside
group_vars
:
$ touch group_vars/cisco.yml group_vars/juniper.yml
Create
mx1.yml
and
csr1.yml
inside
host_vars
:
$ touch host_vars/csr1.yml host_vars/mx1.yml
Populate variables in all the files, as shown here:
$echo 'hostname: core-mx1' >> host_vars/mx1.yml
$echo 'hostname: core-mx2' >> host_vars/mx2.yml
$echo 'hostname: edge-csr1' >> host_vars/csr1.yml
$echo 'hostname: edge-csr2' >> host_vars/csr2.yml
$echo 'os: ios' >> group_vars/cisco.yml
$echo 'os: junos' >> group_vars/juniper.yml
We created the following structure of directories and files to host our variables, as shown in the following diagram:
All files inside the group_vars directory contain the group variables for the groups that we have defined in our inventory and they apply to all the hosts within this group. As for the files within host_vars, they contain variables for each host. Using this structure, we can group variables from multiple hosts into a specific group file and variables that are host-specific will be placed in a separate file specific to this host.
In addition to host_vars and group_vars, Ansible supports the definition of variables using other techniques, including the following:
Using the
vars
keyword within the play to specify multiple variables
Using
vars_files
to define variables in a file and having Ansible read these variables from this file while running the playbook
Specifying variables at the command line using the
--e
option
In addition to the user-defined variables that we can specify, Ansible has some default variables that it builds dynamically for its inventory. The following table captures some of the most frequently used variables:
inventory_hostname
The name of the hosts as defined in the inventory (for example,
csr1
and
mx1
)
play_hosts
A list of all the hosts included in the play
group_names
A list of all the groups that a specific host is a part of (for example, for
csr1
this will be [edge, Cisco, network])
An Ansible playbook is the fundamental element in Ansible that declares what actions we would like to perform on our managed hosts (specified in the inventory). An Ansible playbook is a YAML-formatted file that defines a list of tasks that will be executed on our managed devices. In this recipe, we will outline how to write an Ansible playbook and how to define the hosts that will be targeted by this playbook.
In order to follow along with this recipe, an Ansible inventory file must already be defined, along with all the group- and host-specific variable files created in accordance with previous recipes.
Create a new file called
playbook.yml
inside the
ch1_ansible
folder and incorporate the following lines in this file:
$ cat playbook.yml
---
- name: Initial Playbook
hosts: all
gather_facts: no
tasks:
- name: Display Hostname
debug:
msg: "Router name is {{ hostname }}"
- name: Display OS
debug:
msg: "{{ hostname }} is running {{ os }}"
Run the playbook as shown here:
$ ansible-playbook -i hosts playbook.yml
The Ansible playbook is structured as a list of plays and each play targets a specific group of hosts (defined in the inventory file). Each play can have one or more tasks to execute against the hosts in this play. Each task runs a specific Ansible module that has a number of arguments. The general structure of the playbook is outlined in the following screenshot:
In the preceding playbook, we reference the variables that we defined in the previous recipe inside the {{ }} brackets. Ansible reads these variables from either group_vars or host_vars, and the module that we used in this playbook is the debug module, which displays as a custom message specified in the msg parameter to the Terminal output. The playbook run is shown here:
We use the -i option in the ansible-playbook command in order to point to the Ansible inventory file, which we will use as our source to construct our inventory.
One of the core features of Ansible is conditional task execution. This provides us with the ability to control which tasks to run on a given host based on a condition/test that we specify. In this recipe, we will outline how to configure conditional task execution.
In order to follow along with this recipe, an Ansible inventory file must be present and configured as outlined in the previous recipes. Furthermore, the Ansible variables for all our hosts should be defined as outlined in the previous recipes.
Ansible uses the when statement to provide conditional execution for the tasks. The when statement is applied at the task level and if the condition in the when statement evaluates to true, the task is executed for the given host. If false, the task is skipped for this host. The output as a result of running the preceding playbook is shown here:
The when
