Learning Ansible 2 - Second Edition - Fabio Alessandro Locati - E-Book

Learning Ansible 2 - Second Edition E-Book

Fabio Alessandro Locati

0,0
38,39 €

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

Mehr erfahren.
Beschreibung

Learn everything you need to manage and handle your systems with ease with Ansible 2 using this comprehensive guide

About This Book

  • Simplify the automation of applications and systems using the newest version of Ansible
  • Get acquainted with fundamentals of Ansible such as playbooks, modules, and various testing strategies
  • A comprehensive, learning guide that provides you with great skills to automate your organization's infrastructure using Ansible 2

Who This Book Is For

The book is for sys admins who want to automate their organization's infrastructure using Ansible 2. No prior knowledge of Ansible is required.

What You Will Learn

  • Set up Ansible 2 and an Ansible 2 project in a future-proof way
  • Perform basic operations with Ansible 2 such as creating, copying, moving, changing, and deleting files, and creating and deleting users
  • Deploy complete cloud environments using Ansible 2 on AWS and DigitalOcean
  • Explore complex operations with Ansible 2 (Ansible vault, e-mails, and Nagios)
  • Develop and test Ansible playbooks
  • Write a custom module and test it

In Detail

Ansible is an open source automation platform that assists organizations with tasks such as configuration management, application deployment, orchestration, and task automation. With Ansible, even complex tasks can be handled easier than before.

In this book, you will learn about the fundamentals and practical aspects of Ansible 2 by diving deeply into topics such as installation (Linux, BSD, and Windows Support), playbooks, modules, various testing strategies, provisioning, deployment, and orchestration. In this book, you will get accustomed with the new features of Ansible 2 such as cleaner architecture, task blocks, playbook parsing, new execution strategy plugins, and modules. You will also learn how to integrate Ansible with cloud platforms such as AWS. The book ends with the enterprise versions of Ansible, Ansible Tower and Ansible Galaxy, where you will learn to interact Ansible with different OSes to speed up your work to previously unseen levels

By the end of the book, you'll able to leverage the Ansible parameters to create expeditious tasks for your organization by implementing the Ansible 2 techniques and paradigms.

Style and approach

This book is a step-by-step learning guide on the all new Ansible 2, which is an ideal configuration management tool.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 294

Veröffentlichungsjahr: 2016

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.



Table of Contents

Learning Ansible 2 Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers 
What you need for this book 
Who this book is for
Conventions 
Reader feedback
Customer support
Downloading the example code 
Errata
Piracy
Questions
1. Getting Started with Ansible
IT automation
The history of IT automation
Advantages of IT automation
Disadvantages of IT automation
Limiting the possible damages of an error propagation
Types of IT automation
Agent-based systems
Agent-less systems
Agent-based versus Agent-less systems
What is Ansible?
Secure Shell (SSH)
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 QEMU and KVM
Version control system
Using Ansible with Git
Summary
2. Automating Simple Tasks
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
3. Scaling to Multiple Hosts
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 inventory
Amazon Web Services
DigitalOcean
Working with iterates in Ansible
Standard iteration - with_items
Nested loops - with_nested
Fileglobs loop - with_fileglobs
Integer loop - with_sequence
Summary
4. Handling Complex Deployment
Working with the local_action feature
Delegating a task
Working with conditionals
Boolean conditionals
Checking if a variable is set
Working with include
Working with handlers
Working with roles
Project organization
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
Tasks blocks
The Ansible template - Jinja filters
Formatting data using filters
Using filters with conditionals
Defaulting undefined variables
Security management
Using Ansible vault
Vaults and playbooks
Encrypting user passwords
Hiding passwords
Using no_log
Summary
5. Going Cloud
Provisioning resources in the cloud
Amazon Web Service
AWS global infrastructure
AWS Simple Storage Service
AWS Elastic Compute Cloud (EC2)
AWS Virtual Private Cloud (VPC)
AWS Route 53
AWS Elastic Block Storage (EBS)
AWS Identity and Access Management
Amazon relational database service
Setting up an account with AWS
Simple AWS deployment
Complex AWS deployment
DigitalOcean
Droplets
SSH key management
Private networking
Adding an SSH key in DigitalOcean
Deployment in DigitalOcean
Summary
6. Getting Notifications from Ansible
E-mails
XMPP
Slack
Rocket Chat
Internet Relay Chat (IRC)
Amazon Simple Notification Service
Nagios
Summary
7. Creating a Custom Module
Using Python modules
Working with exit_json and fail_json
Testing Python modules
Using bash modules
Using Ruby modules
Testing modules
Summary
8. Debugging and Error Handling
The check mode
Indicating differences between files using --diff
Functional testing in Ansible
Functional testing using assert
Testing with tags
The --skip-tags
Managing exceptions
Trigger failure
Summary
9. Complex Environments
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 revision control systems
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
10. Introducing Ansible for Enterprises
Ansible on Windows
Ansible for networking devices
Ansible Galaxy
Ansible Tower
Summary

Learning Ansible 2 Second Edition

Learning Ansible 2 Second Edition

Copyright © 2016 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: November 2014

Second edition: November 2016

Production reference: 1161116

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-423-1

www.packtpub.com

Credits

Authors

Fabio Alessandro Locati

Copy Editor

Madhusudan Uchil

Reviewers

Tim Rupp 

Project Coordinator

Judie Jose 

Commissioning Editor

Pratik Shah

Proofreader

Safis Editing

Acquisition Editor

Divya Poojari 

Indexer

Pratik Shirodkar 

Content Development Editor

Amedh Gemraram Pohad

Graphics

Kirk D'Penha

Technical Editor

Vishal Kamal Mewada

Production Coordinator

Shantanu N. Zagade

About the Author

Fabio Alessandro Locati is a senior consultant at Red Hat, public speaker, author, and open source contributor. His main areas of expertise are Linux, security, cloud technologies, and automation. With more than 10 years of working experience in the field, he has experience in different IT roles, technologies, and languages.

He has worked for many different companies, starting from a one-man company to huge companies such as Tech Data and Samsung. This has allowed him to consider various technologies from different points of view, helping him develop critical thinking and swiftly understand whether a particular technology is the right fit for a specific project.

Since he is always looking for better technologies, he also tries new technologies to understand their advantages over the old ones as well as their maturity status. One of the most important things he evaluates about a technology is its internal security and the possibility of adding security through configuration or interaction with other technologies.

In his work and to manage his own machines, he has used Ansible since 2013.

He often gives talks about his work, the projects he helps with in his spare time, and his vision of the IT and security worlds. He is the author of the book OpenStack Cloud Security, Packt Publishing.

In his spare time, he helps out on the Fedora Project as well as Wikimedia and Open Street Map.

You can find more about him on LinkedIn at https://www.linkedin.com/in/fabiolocati/en and at https://fale.io/.

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 Publishing for their hard work and to Tim Rupp  for his great feedbacks. Since Ansible is an open source project, I thank all companies that decided to invest into it as well as all people that decided to volunteer their time to the project.

About the Reviewer

Tim Rupp has been working in various fields of computing for the last 10 years. He has held positions in computer security, software engineering, and, most recently, in the fields of cloud computing and DevOps.

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 the Rackspace public cloud. Since then, he has contributed patches, provided support for, and presented on Ansible topics at local meetups.

Tim is currently a senior software engineer at F5 Networks, where he works on data plane programmability. He is particularly interested in automation and orchestration surrounding F5 products and is the maintainer of the BIG-IP modules in Ansible.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.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.PacktPub.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.PacktPub.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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

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 to change infrastructures at 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, compute, what have you), will be key, but those technologies need to be managed in an equally scalable way, and that way will be using Ansible and similar products.

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

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 offering and how it can simplify your life, managing the cloud for you.

Chapter 6, Getting Notifications 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, multiple 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 and Ansible Tower to maximize your productivity.

What you need for this book 

This book is written to work with all Linux distributions. Since it’s not practical to always give the same information for all possible distributions, the example commands are for Fedora on the controller machine and CentOS on the controlled machines, if not stated. Experienced users with other distributions will have no problem in translating the commands for their own preferred distribution.

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.

Conventions 

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The ec2.py file will create multiple groups based on the region, availability zone, tags, and so on."

A block of code is set as follows:

--- - hosts: all   remote_user: ansible   vars:     users:     - alice     - bob     folders:     - mail     - public_html

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: ansible   vars:     users:     - alice    - bob     folders:     - mail    - public_html

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

$ ansible-playbook -i test01.fale.io, webserver.yaml

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code 

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Ansible-2-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Getting Started with Ansible

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

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 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 like Amazon Web Services, Facebook, and Google. It is the implementation of IT automation systems to create and manage servers.

In this chapter we will cover:

IT automationWhat is Ansible?The secure shellInstalling AnsibleCreating a test environment with QEMU and KVMVersion control systemUsing Ansible with Git

IT automation

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

The history of IT automation

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 life 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 advantages of IT automation are:

Ability to provision machines quicklyAbility to recreate a machine from scratch in minutesAbility 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 administratorsIf 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.

Limiting the possible damages of an error propagation

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 could 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 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 nuking a machine while trying to clean an application temporary folder.Use horizontal privilege escalation: The sudo is a well-known command 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 a dev, test, staging, and qa environment. The majority of them are related to 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 if 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 the verbose mode for grep and -h is not the 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 command safe, you have to assume that a dd command is dangerous, since dd perform 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 that; "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. If 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 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 if they are not empty 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 Linux shells. They could also be very dangerous: a cat /dev/rand > /dev/sda command can destroy a disk even if a cat 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.

Note

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, 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 that will contact the client(s) using standard protocols (usually via SSH and PowerShell).

Agent-based versus Agent-less systems

Aside from the differences outlined above, there are other contrasting factors which 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 and 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 wait to implement such feature. 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, since it will be seen by the clients as a normal SSH connection and 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 has recently been bought out by Red Hat 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 is a large number of machines (large is a relative term; in our view, greater than 500 and requiring parallel updates), and you plan to deploy updates to the machines in parallel, this might be the right way to go about it.

Secure Shell (SSH)

Secure Shell (also known as SSH) is a network service that allows you to login and access a shell remotely in 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 months, Microsoft has shown an implementation (at the time of writing) of OpenSSH for Windows.

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 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 with 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 need to take care of the order, and the Puppet server will create the sequence of instructions to execute every time you run it on a different box. 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). You can use Ansible on any Windows, Mac, or UNIX-like system. Ansible doesn't require any databases and doesn't need any daemons running. This makes it easier to maintain Ansible versions and upgrade without any breaks.

We'd like to call the machine where we will install Ansible our Ansible workstation. Some people also refer to it as the command center.

Installing Ansible using the system's package manager

It is possible to install Ansible using the system's package manager and in my opinion this is the preferred option if your system's package manager ships at least Ansible 2.0. We will look into installing Ansible via Yum, Apt, Homebrew, and pip.

Installing via Yum

If you are running a Fedora system you can install Ansible directly, since from Fedora 22, Ansible 2.0+ is available in the official repositories. You can install it as follows:

$ sudo dnf install ansible

For RHEL and RHEL-based (CentOS, Scientific Linux, Unbreakable Linux) systems, versions 6 and 7 have Ansible 2.0+ available in the EPEL repository, so you should ensure that you have the EPEL repository enabled before installing Ansible as follows:

$ sudo yum install ansible

Note

On Cent 6 or RHEL 6, you have to run the command rpm -Uvh. Refer to http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm for instructions on how to install EPEL.

Installing via Apt

Ansible is available for Ubuntu and Debian. To install Ansible on those operating systems, use the following command:

$ sudo apt-get install ansible

Installing via Homebrew

You can install Ansible on Mac OS X using Homebrew, as follows:

$ brew update$ brew install ansible