Learning Ansible 2.7 - Fabio Alessandro Locati - E-Book

Learning Ansible 2.7 E-Book

Fabio Alessandro Locati

0,0
32,36 €

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

Mehr erfahren.
Beschreibung

Use Ansible to configure your systems, deploy software, and orchestrate advanced IT tasks




Key Features



  • Get familiar with the fundamentals of Ansible 2.7


  • Understand how to use Ansible Tower to scale your IT automation


  • Gain insights into how to develop and test Ansible playbooks





Book Description



Ansible is an open source automation platform that assists organizations with tasks such as application deployment, orchestration, and task automation. With the release of Ansible 2.7, even complex tasks can be handled much more easily than before.







Learning Ansible 2.7 will help you take your first steps toward understanding the fundamentals and practical aspects of Ansible by introducing you to topics such as playbooks, modules, and the installation of Linux, Berkeley Software Distribution (BSD), and Windows support. In addition to this, you will focus on various testing strategies, deployment, and orchestration to build on your knowledge. The book will then help you get accustomed to features including cleaner architecture, task blocks, and playbook parsing, which can help you to streamline automation processes. Next, you will learn how to integrate Ansible with cloud platforms such as Amazon Web Services (AWS) before gaining insights into the enterprise versions of Ansible, Ansible Tower and Ansible Galaxy. This will help you to use Ansible to interact with different operating systems and improve your working efficiency.







By the end of this book, you will be equipped with the Ansible skills you need to automate complex tasks for your organization.





What you will learn



  • Create a web server using Ansible


  • Write a custom module and test it


  • Deploy playbooks in the production environment


  • Troubleshoot networks using Ansible


  • Use Ansible Galaxy and Ansible Tower during deployment


  • Deploy an application with Ansible on AWS, Azure and DigitalOcean





Who this book is for



This beginner-level book is for system administrators who want to automate their organization's infrastructure using Ansible 2.7. No prior knowledge of Ansible is required

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

EPUB

Seitenzahl: 292

Veröffentlichungsjahr: 2019

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.



Learning Ansible 2.7Third Edition

 

Automate your organization's infrastructure using Ansible 2.7

 

 

 

 

 

 

 

 

 

 

 

Fabio Alessandro Locati

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Learning Ansible 2.7 Third Edition

Copyright © 2019 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: Karan SadawanaAcquisition Editor: Prachi BishtContent Development Editor: Drashti PanchalTechnical Editor: Komal KarneCopy Editor:Safis EditingProject Coordinator: Jagdish PrabhuProofreader: Safis EditingIndexer: Manju ArasanGraphics: Tom ScariaProduction Coordinator: Nilesh Mohite

First published: November 2014 Second edition: November 2016 Third edition: April 2019

Production reference: 1300419

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78995-433-3

www.packtpub.com

 
mapt.io

Mapt is an online digital library that gives you full access to over 5,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.

Why subscribe?

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

Mapt is fully searchable

Copy and paste, print, and bookmark content

Packt.com

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. 

Contributors

About the author

Fabio Alessandro Locati, commonly known as Fale, is a director at Otelia, a public speaker, an author, and an open source contributor. His main areas of expertise are Linux, automation, security, and cloud technologies. Fale has more than 12 years of working experience in IT, with many of them spent consulting for many companies, including dozens of Fortune 500 companies. This has allowed him to consider technologies from different points of view, and to think critically about them.

I would like to thank my parents, who introduced me to computer science before I was even able to write, and my whole family, who has always been supportive. A special thanks goes to everyone I worked with at Packt for their hard work, and to Timothy Rupp for his great feedback. Since Ansible is an open source project, I thank all the companies that decided to invest in it, and all the people that decided to volunteer their time to the project.

About the reviewer

Timothy Rupp has been working in various fields of computing for the last 15 years. He has held positions in cybersecurity, software engineering, and in the cloud computing and DevOps fields.

He was first introduced to Ansible while at Rackspace. As part of the cloud engineering team, he made extensive use of the tool to deploy new capacity for Rackspace Public Cloud. Since that introduction, he has contributed patches, provided support, and presented on Ansible topics at local meetups.

While at F5 Networks, he led the development of F5's Ansible modules, and became a core contributor to the Ansible project. Most recently, he has become re-involved in cybersecurity in the financial sector.

 

 

 

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Learning Ansible 2.7 Third Edition

About Packt

Why subscribe?

Packt.com

Contributors

About the author

About the reviewer

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

Conventions used

Get in touch

Reviews

Section 1: Creating a Web Server Using Ansible

Getting Started with Ansible

Technical requirements

IT automation

Advantages of IT automation

Disadvantages of IT automation

Types of IT automation

Agent-based systems

Agent-less systems

Agent-based versus agent-less systems

What is Ansible?

Secure Shell

Why Ansible?

Installing Ansible

Installing Ansible using the system's package manager

Installing via Yum

Installing via Apt

Installing via Homebrew

Installing via pip

Installing Ansible from source

Creating a test environment with Vagrant

Version control systems

Using Ansible with Git

Summary

Automating Simple Tasks

Technical Requirement

YAML

Hello Ansible

Working with playbooks

Studying the anatomy of a playbook

Running a playbook

Ansible verbosity

Variables in playbooks

Creating the Ansible user

Configuring a basic server

Enabling EPEL

Installing Python bindings for SELinux

Upgrading all installed packages

Ensuring that NTP is installed, configured, and running

Ensuring that FirewallD is present and enabled

Adding a customized MOTD

Changing the hostname

Reviewing and running the playbook

Installing and configuring a web server

Publishing a website

Jinja2 templates

Variables

Filters

Conditionals

Cycles

Summary

Section 2: Deploying Playbooks in a Production Environment

Scaling to Multiple Hosts

Technical requirements 

Working with inventory files

The basic inventory file

Groups in an inventory file

Regular expressions in the inventory file

Working with variables

Host variables

Group variables

Variable files

Overriding configuration parameters with an inventory file

Working with dynamic inventories

Amazon Web Services

DigitalOcean

Working with iterates in Ansible

Using standard iteration – with_items

Using nested loops – with_nested

Fileglobs loop – with_fileglobs

Using an integer loop – with_sequence

Summary

Handling Complex Deployment

Technical requirements

Working with the local_action feature

Delegating a task

Working with conditionals

Boolean conditionals

Checking whether a variable is set

Working with include

Working with handlers

Working with roles

Organizing a project

Anatomy of a role

Transforming your playbooks in a full Ansible project

Transforming a playbook into a role

Helper files

Transforming the webserver role

Handlers in roles

Execution strategies

The Ansible template – Jinja filters

Formatting data using filters

Defaulting undefined variables

Security management

Using Ansible Vault

Vaults and playbooks

Encrypting user passwords

Hiding passwords

Using no_log

Summary

Going Cloud

Technical requirements

Provisioning resources in the cloud

Provisioning machines in AWS

AWS global infrastructure

AWS Simple Storage Service 

AWS Elastic Compute Cloud 

AWS Virtual Private Cloud 

AWS Route 53

AWS Elastic Block Storage

AWS Identity and Access Management

Amazon Relational Database Service 

Setting up an account with AWS

Simple AWS deployment

Complex AWS deployment

Provisioning machines in DigitalOcean

Droplets

SSH key management

Private networking

Adding an SSH key in DigitalOcean

Deployment in DigitalOcean

Provisioning machines in Azure

Summary

Getting Notification from Ansible

Technical requirements 

Sending emails with Ansible

XMPP

Slack

Rocket Chat

Internet Relay Chat

Amazon Simple Notification Service

Nagios

Summary

Section 3: Deploying an Application with Ansible

Creating a Custom Module

Prerequisite

Using Python to write modules

Working with exit_json and fail_json

Testing Python modules

Using bash modules

Using Ruby modules

Testing modules

Summary

Debugging and Error Handling

Technical requirements

Syntax checking

The check mode

Indicating differences between files using --diff

Functional testing in Ansible

Functional testing using assert

Testing with tags

Understanding the --skip-tags option

Understanding debugging commands

Managing exceptions

Trigger failure

Summary

Complex Environments

Technical requirements

Code based on the Git branch

A single stable branch with multiple folders

Software distribution strategy

Copying files from the local machine

Revision control system with branches

Revision control system with tags

RPM packages

Preparing the environment

Deploying a web app with a revision control system

Deploying a web app with RPM packages

Creating a SPEC file

Building RPMs manually

Building RPMs with Ansible

Building RPMs with CI/CD pipelines

Building compiled software with RPM packaging

Deployment strategies

Canary deployment

Blue/green deployment

Optimizations

Pipelining

Optimizing with_items

Understanding what happens when your tasks are executed

Summary

Section 4: Deploying an Application with Ansible

Introducing Ansible for Enterprises

Technical requirements

Ansible on Windows

Ansible Galaxy

Pushing a role to Ansible Galaxy

Ansible Tower and AWX

Summary

Getting Started with AWX

Technical requirements

Setting up AWX

Installing Ansible, Docker, and Docker-py in Fedora

Giving the current user permission to use Docker in Fedora

Installing AWX

Creating new AWX projects

Using AWX inventories

Understanding AWX job templates

Using AWX jobs

Summary

Working with AWX Users, Permissions, and Organizations

Technical requirements

AWX users and permissions

AWX organizations

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

The information technology sector is a fast-moving sector that always tries to accelerate. To keep up with this, companies need to be able to move quickly and iterate frequently. Until a few years back, this was mainly true for software, but now we start to see the necessity of developing infrastructure at a similar speed. Going forward, we will need to change the infrastructure we run our software on at the speed of the software itself.

In this scenario, many technologies, such as software-defined everything (storage, network, and compute, for example), will be key, but those technologies need to be managed in an equally scalable way, and that way will involve using Ansible and similar products.

Ansible is highly relevant today, since, unlike competing products, it is agentless, allowing for faster deployments, more security, and better auditability.

Who this book is for

The book is for developers and sysadmins who want to automate their organization’s infrastructure using Ansible 2. No prior knowledge of Ansible is required.

What this book covers

Chapter 1, Getting Started with Ansible, explains how to install Ansible.

Chapter 2, Automating Simple Tasks, explains how to create simple playbooks that will allow you to automate some simple tasks that you already perform on a daily basis.

Chapter 3, Scaling to Multiple Hosts, explains how to handle multiple hosts in Ansible in an easy-to-scale way.

Chapter 4, Handling Complex Deployment, explains how to create deployments that have multiple phases, as well as multiple machines.

Chapter 5, Going Cloud, explains how Ansible can integrate with various cloud offerings, and how it can simplify your life, managing the cloud for you.

Chapter 6, Getting Notification from Ansible, explains how to set up Ansible to return valuable information to you and other stakeholders.

Chapter 7, Creating a Custom Module, explains how to create a custom module to leverage the freedom Ansible gives you.

Chapter 8, Debugging and Error Handling, explains how to debug and test Ansible to ensure that your playbooks will always work.

Chapter 9, Complex Environments, explains how to manage multiple tiers, environments, and deployments with Ansible.

Chapter 10, Introducing Ansible for Enterprises, explains how to manage Windows nodes from Ansible, as well as how to leverage Ansible Galaxy to maximize your productivity.

Chapter 11, Getting Started with AWX, explains what AWX is and how you can start using it.

Chapter 12,Working with AWX Users, Permissions, and Organizations, explains how AWX users and permissions management works.

To get the most out of this book

This book assumes a basic knowledge of the UNIX shell, as well as basic networking knowledge.

Download the example code files

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.packt.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 & Errata

.

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 athttps://github.com/PacktPublishing/Learning-Ansible-2.X-Third-Edition. 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!

 

Conventions used

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: "The sudo command is a well known, but is often used in its more dangerous form."

A block of code is set as follows:

- hosts: all remote_user: vagrant tasks: - name: Ensure the HTTPd package is installed yum: name: httpd state: present become: True

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

- hosts: all remote_user: vagrant tasks:

- name: Ensure the HTTPd package is installed

yum: name: httpd state: present become: True

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

$ sudo dnf install ansible

Warnings or important notes appear like this.
Tips and tricks 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, 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.packt.com/submit-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.

Reviews

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.

Section 1: Creating a Web Server Using Ansible

This section will help you create simple playbooks that will allow you to automate some simple tasks that you already perform on a daily basis.

This section contains the following chapters:

Chapter 1

,

 

Getting Started with Ansible

Chapter 2

,

 

Automating Simple Tasks

Getting Started with Ansible

Information and communications technology (ICT) is often described as a fast-growing industry. I think that the best quality of the ICT industry is not related to its ability to grow at a super-high speed, but is related to its ability to revolutionize itself, and the rest of the world, at an astonishing pace.

Every 10 to 15 years there are major shifts in how this industry works, and every shift solves problems that were very hard to manage up to that point, creating new challenges. Also, at every major shift, many of the best practices of the previous iteration are classified as anti-patterns, and new best practices are created. Although it might appear that those changes are impossible to predict, this is not always true. Obviously, it is not possible to know exactly what changes will occur and when they will take place, but looking at companies with a large number of servers and many lines of code usually reveals what the next steps will be.

The current shift has already happened in big companies such as Amazon Web Services (AWS), Facebook, and Google. It is the implementation of IT automation systems to create and manage servers.

In this chapter we will cover the following topics:

IT automation

What is Ansible?

The secure shell

Installing Ansible

Creating a test environment with Vagrant

Version control systems

Using Ansible with Git

Technical requirements

To support the learning of Ansible, I suggest having a machine where you can install Vagrant. Using Vagrant will allow you to try many operations, even destructive ones, without fear.

Additionally, AWS and Azure accounts are suggested, since some examples will be on those platforms.

All examples in this book are available in the GitHub repository at https://github.com/PacktPublishing/-Learning-Ansible-2.X-Third-Edition/.

IT automation

IT automation is – in its broader sense – the processes and software that help with the management of the IT infrastructure (servers, networking, and storage). In the current shift, we are supporting for a huge implementation of such processes and software.

At the beginning of IT history, there were very few servers, and a lot of people were needed to make them work properly, usually more than one person for each machine. Over the years, servers became more reliable and easier to manage, so it was possible to have multiple servers managed by a single system administrator. In that period, the administrators manually installed the software, upgraded the software manually, and changed the configuration files manually. This was obviously a very labor-intensive and error-prone process, so many administrators started to implement scripts and other means to make their lives easier. Those scripts were (usually) pretty complex, and they did not scale very well.

In the early years of this century, data centers started to grow a lot due to companies' needs. Virtualization helped in keeping prices low, and the fact that many of these services were web services meant that many servers were very similar to each other. At this point, new tools were needed to substitute the scripts that were used before: the configuration management tools.

CFEngine was one of the first tools to demonstrate configuration management capabilities way back in the 1990s; more recently, there has been Puppet, Chef, and Salt, besides Ansible.

Advantages of IT automation

People often wonder if IT automation really brings enough advantages, considering that implementing it has some direct and indirect costs. The main benefits of IT automation are the following:

The ability to provision machines quickly

The ability to recreate a machine from scratch in minutes

The ability to track any change performed on the infrastructure

For these reasons, it's possible to reduce the cost of managing the IT infrastructure by reducing the repetitive operations often performed by system administrators.

Disadvantages of IT automation

As with any other technology, IT automation does come with some disadvantages. From my point of view, these are the biggest disadvantages:

Automating all of the small tasks that were once used to train new system administrators.

If an error is performed, it will be propagated everywhere.

The consequence of the first is that new ways to train junior system administrators will need to be implemented.

The second one is trickier. There are a lot of ways to limit this kind of damage, but none of those will prevent it completely. The following mitigation options are available:

Always have backups

: Backups will not prevent you from nuking your machine – they will only make the restore process possible.

Always test your infrastructure code (playbooks/roles) in a non-production environment

: Companies have developed different pipelines to deploy code, and those usually include environments such as dev, test, staging, and production. Use the same pipeline to test your infrastructure code. If a buggy application reaches the production environment it could be a problem. If a buggy playbook reaches the production environment, it can be catastrophic.

Always peer-review your infrastructure code

: Some companies have already introduced peer-reviews for the application code, but very few have introduced it for the infrastructure code. As I was saying in the previous point, I think that infrastructure code is way more critical than application code, so you should always peer-review your infrastructure code, whether you do it for your application code or not.

Enable SELinux

: SELinux is a security kernel module that is available on all Linux distributions (it is installed by default on Fedora, Red Hat Enterprise Linux, CentOS, Scientific Linux, and Unbreakable Linux). It allows you to limit users and process powers in a very granular way. I suggest using SELinux instead of other similar modules (such as AppArmor) because it is able to handle more situations and permissions. SELinux will prevent a huge amount of damage because, if correctly configured, it will prevent many dangerous commands from being executed.

Run the playbooks from a limited account

: Even though user and privilege escalation schemes have been in Unix code for more than 40 years, it seems as if not many companies use them. Using a limited user for all your playbooks, and escalating privileges only for commands that need higher privileges, will help prevent you from nuking a machine while trying to clean an application temporary folder.

Use horizontal privilege escalation

: The

sudo

 command is a well known, but is often used in its more dangerous form. The

sudo

command supports the

-u

 parameter that will allow you to specify a user that you want to impersonate. If you have to change a file that is owned by another user, please do not escalate to

root

to do so, just escalate to that user. In Ansible, you can use the

become_user

parameter to achieve this.

When possible, don't run a playbook on all your machines at the same time

: Staged deployments can help you detect a problem before it's too late. There are many problems that are not detectable in dev, test, staging, and QA environments. The majority of them are related to a load that is hard to emulate properly in those non-production environments. A new configuration you have just added to your Apache HTTPd or MySQL servers could be perfectly OK from a syntax point of view, but disastrous for your specific application under your production load. A staged deployment will allow you to test your new configuration on your actual load without risking downtime in case something was wrong.

Avoid guessing commands and modifiers

: A lot of system administrators will try to remember the right parameter, and try to guess if they don't remember it exactly. I've done it too, a lot of times, but this is very risky. Checking the man page or the online documentation will usually take you less than two minutes, and often, by reading the manual, you'll find interesting notes you did not know. Guessing modifiers is dangerous because you could be fooled by a non-standard modifier (that is,

-v

is not a verbose mode for

grep

, and

-h

is not a 

help

command for the MySQL CLI).

Avoid error-prone commands

: Not all commands have been created equally. Some commands are (way) more dangerous than others. If you can assume a

cat

-based command safe, you have to assume that a

dd

-based command is dangerous, since it performs copies and conversion of files and volumes. I've seen people using

dd

in scripts to transform DOS files to Unix (instead of

dos2unix

) and many other, very dangerous, examples. Please, avoid such commands, because they could result in a huge disaster if something goes wrong.

Avoid unnecessary modifiers

: If you need to delete a simple file, use

rm ${file}

, not

rm -rf ${file}

. The latter is often performed by users that have learned 

to be sure, always use

rm -rf

, because at some time in their past, they have had to delete a folder. This will prevent you from deleting an entire folder if the

${file}

variable is set wrongly.

Always check what could happen if a variable is not set

: If you want to delete the contents of a folder and you use the

rm -rf ${folder}/*

command, you are looking for trouble. In case the

${folder}

variable is not set for some reason, the shell will read a

rm -rf /*

command, which is deadly (considering the fact that the

rm -rf /

command will not work on the majority of current OSes because it requires a

--no-preserve-root

option, while the

rm -rf /*

will work as expected). I'm using this specific command as an example because I have seen such situations: the variable was pulled from a database which, due to some maintenance work, was down, and an empty string was assigned to that variable. What happened next is probably easy to guess. In case you cannot prevent using variables in dangerous places, at least check them to see whether they are empty or not before using them. This will not save you from every problem, but may catch some of the most common ones.

Double-check your redirections

: Redirections (along with pipes) are the most powerful elements of Unix shells. They could also be very dangerous: a

cat /dev/rand > /dev/sda

can destroy a disk even if a

cat

-based command is usually overlooked because it's not usually dangerous. Always double-check all commands that include a redirection.

Use specific modules wherever possible

: In this list, I've used shell commands because many people will try to use Ansible as if it's just a way to distribute them: it's not. Ansible provides a lot of modules and we'll see them in this book. They will help you create more readable, portable, and safe playbooks.

Types of IT automation

There are a lot of ways to classify IT automation systems, but by far the most important is related to how the configurations are propagated. Based on this, we can distinguish between agent-based systems and agent-less systems.

Agent-based systems

Agent-based systems have two different components: a server, and a client called agent.

There is only one server, and it contains all of the configuration for your whole environment, while the agents are as many as the machines in the environment.

In some cases, more than one server could be present to ensure high availability, but treat it as if it's a single server, since they will all be configured in the same way.

Periodically, the client will contact the server to see if a new configuration for its machine is present. If a new configuration is present, the client will download it and apply it.

Agent-less systems

In agent-less systems, no specific agent is present. Agent-less systems do not always respect the server/client paradigm, since it's possible to have multiple servers and even the same number of servers and clients. Communications are initialized by the server, which will contact the client(s) using standard protocols (usually via SSH and PowerShell).

Agent-based versus agent-less systems

Aside from the differences previously outlined, there are other contrasting factors that arise because of those differences.

From a security standpoint, an agent-based system can be less secure. Since all machines have to be able to initiate a connection to the server machine, this machine could be attacked more easily than in an agent-less case, where the machine is usually behind a firewall that will not accept any incoming connections.

From a performance point of view, agent-based systems run the risk of having the server saturated, therefore the roll-out could be slower. It also needs to be considered that, in a pure agent-based system, it is not possible to force-push an update immediately to a set of machines. It will have to wait until those machines check-in. For this reason, multiple agent-based systems have implemented out-of-bands ways to implement such features. Tools such as Chef and Puppet are agent-based, but can also run without a centralized server to scale a large number of machines, commonly called Serverless Chef and Masterless Puppet respectively.

An agent-less system is easier to integrate in an infrastructure that is already present (brownfield) since it will be seen by the clients as a normal SSH connection, therefore no additional configuration is needed.

What is Ansible?

Ansible is an agent-less IT automation tool developed in 2012 by Michael DeHaan, a former Red Hat associate. The Ansible design goals are for it to be minimal, consistent, secure, highly reliable, and easy to learn. The Ansible company was bought by Red Hat in October 2015, and now operates as part of Red Hat, Inc.

Ansible primarily runs in push mode using SSH, but you can also run Ansible using ansible-pull, where you can install Ansible on each agent, download the playbooks locally, and run them on individual machines. If there are a large number of machines (large is a relative term; but in this case, consider it to mean greater than 500), and you plan to deploy updates to the machines in parallel, this might be the right way to go about it. As we discussed before, either agent-full and agent-less systems have their pros and cons.

In the next section, we will discuss Secure Shell (SSH), which is a core part of Ansible and the Ansible philosophy.

Secure Shell

Secure Shell (also known as SSH) is a network service that allows you to log in and access a shell remotely over a fully encrypted connection. The SSH daemon is today the standard for UNIX system administration, after having replaced the unencrypted telnet. The most frequently used implementation of the SSH protocol is OpenSSH.

In the last few years, Microsoft has implemented OpenSSH for Windows. I think that this proves the de facto standard situation that SSH lives into.

Since Ansible performs SSH connections and commands in the same way any other SSH client would do, no specific configuration has been applied to the OpenSSH server.

To speed up default SSH connections, you can always enable ControlPersist and the pipeline mode, which makes Ansible faster and more secure.

Why Ansible?

We will try and compare Ansible with Puppet and Chef during the course of this book, since many people have good experience those tools. We will also point out specifically how Ansible would solve a problem compared to Chef or Puppet.

Ansible, as well as Puppet and Chef, are declarative in nature, and are expected to move a machine to the desired state specified in the configuration. For example, in each of these tools, in order to start a service at a point in time and start it automatically on restart, you would need to write a declarative block or module; every time the tool runs on the machine, it will aspire to obtain the state defined in your playbook (Ansible), cookbook (Chef), or manifest (Puppet).

The difference in the toolset is minimal at a simple level, but as more situations arise and the complexity increases, you will start finding differences between the different toolsets. In Puppet, you do not set the order in which the tasks will be executed, and the Puppet server will decide the sequence and the parallelizations at runtime, making it easier to end up with difficult-to-debug errors. To exploit the power of Chef, you will need a good Ruby team. Your team needs to be good at the Ruby language to customize both Puppet and Chef, and there will be a bigger learning curve with both of the tools.

With Ansible, the case is different. It uses the simplicity of Chef when it comes to the order of execution – the top-to-bottom approach – and allows you to define the end state in YAML format, which makes the code extremely readable and easy for everyone, from development teams to operations teams, to pick up and make changes. In many cases, even without Ansible, operations teams are given playbook manuals to execute instructions from whenever they face issues. Ansible mimics that behavior. Do not be surprised if you end up having your project manager change the code in Ansible and check it into Git because of its simplicity!

Installing Ansible

Installing Ansible is rather quick and simple. You can use the source code directly, by cloning it from the GitHub project (https://github.com/ansible/ansible); install it using your system's package manager; or use Python's package management tool (pip