Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Ansible For Security by Examples
Ansible For Security by Examples
Ansible For Security by Examples
Ebook881 pages4 hours

Ansible For Security by Examples

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Ansible is an Open Source IT automation tool. This book contains all of the obvious and not-so-obvious best practices of Ansible automation for Security and Compliance.

Every successful IT department needs automation nowadays for bare metal servers, virtual machines, could, containers, and edge computing. Automate your IT journey with Ansi

LanguageEnglish
PublisherLuca Berton
Release dateApr 19, 2022
ISBN9788090853676
Ansible For Security by Examples
Author

Berton

Luca Berton is an Ansible Automation Engineer of Red Hat, based in Brno - Czech Republic. With more than 15 years of experience as a System Administrator, he has strong expertise in Infrastructure Hardening and Automation. Enthusiast of the Open Source supports the community sharing his knowledge in different events of public access. Geek by nature, Linux by choice, Fedora of course.

Read more from Berton

Related to Ansible For Security by Examples

Related ebooks

Computers For You

View More

Reviews for Ansible For Security by Examples

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Ansible For Security by Examples - Berton

    Ansible For Security by Examples

    Ansible For Security by Examples

    100+ Automation Examples to Automate Security and Verify Compliance for IT Modern Infrastructure

    Luca Berton

    This book is for sale at http://leanpub.com/ansibleforsecuritybyexamples

    This version was published on 2022-04-08

    publisher's logo

    *   *   *   *   *

    This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

    *   *   *   *   *

    © 2022 Luca Berton

    ISBN for EPUB version: 978-80-908536-7-6

    ISBN for MOBI version: 978-80-908536-8-3

    Table of Contents

    Introduction

    Whois Luca Berton

    Ansible For Beginners With Examples

    What is Ansible

    Getting Started

    Inventory

    Playbook

    Variables

    Facts and Magic Variables

    Vault

    Conditional

    Loop

    Handler

    Role

    Ansible Best Practices

    Install Ansible

    Ansible terminology - ansible vs ansible-core packages

    How to install Ansible in RedHat Enterprise Linux (RHEL) 8 with Ansible Engine

    How to install Ansible in Ubuntu 20.04

    How to install Ansible in Fedora 35

    How to install Ansible in CentOS 9 Stream

    How to install Ansible in Windows 11 WSL Windows Subsystem for Linux

    How to install Ansible in SUSE Linux Enterprise Server (SLES) 15 SP3

    How to install Ansible with PIP

    How to install Ansible in RedHat Enterprise Linux 9 Beta

    How to install Ansible in Amazon Linux 2 (AWS EC2)

    How to install Ansible in Debian 11

    Ansible For Linux

    Ansible terminology - ansible_hostname vs inventory_hostname vs ansible_fqdn

    Three options to Safely Limit Ansible Playbooks Execution to a Single Machine

    Ansible modules - command vs shell

    Test host availability - Ansible module ping

    How to print a text or a variable during the execution with Ansible

    Edit single-line text - Ansible module lineinfile

    Edit multi-line text - Ansible module blockinfile

    Pause execution - Ansible module pause

    Execute command on the Ansible host - Ansible localhost

    Read a file into a variable on host - Ansible lookup plugin file

    Reboot remote hosts - Ansible module reboot

    Checkout git repository via HTTPS - Ansible module git

    Checkout git repository via SSH - Ansible module git

    Copy files to remote hosts - Local to Remote - Ansible module copy

    Copy files from remote hosts - Remote to Local - Ansible module fetch

    Start and enable services on boot on Linux remote hosts - Ansible module service_facts, service

    Restart services on remote hosts - Ansible module service

    Stop and disable services on boot on remote hosts - Ansible module service_facts, service

    Apply a file template - Ansible module template - HTML placeholder

    Loop in file template - Ansible module template - Generate hosts file

    Schedule a Cron Job task in Linux - Ansible module cron

    How to Pass Variables to Ansible Playbook in command line? - Ansible extra variables

    Break a string over multiple lines - Ansible Literal and Folded Block Scalar operators

    Read a file from remote hosts - Ansible module slurp

    Read an environment variable - Ansible lookup plugin env"

    Set remote environment per task or play - Ansible environment statement

    Permanently Set Remote System Wide Environment Variables on Linux - /etc/environment - Ansible module lineinfile

    Ansible Code reuse: Roles and Collections with Ansible Galaxy

    Download and Use Ansible Galaxy Role - ansible-galaxy and requirements.yml

    Download and Use Ansible Galaxy Collection - ansible-galaxy and requirements.yml

    Ansible for Linux Filesystem

    Create an empty file - Ansible module file

    Create a text file - Ansible module copy

    Check if a file exists - Ansible module stat

    How to create a directory with Ansible?

    How to check if a directory exists in Ansible?

    How to rename a file or directory using an Ansible task on a remote system?

    Change file permission - Ansible module file

    Add Execute Permission 755 Linux file - Ansible module file

    Delete file or directory - Ansible module file

    Download a file - Ansible module get_url

    Extract an archive - Ansible module unarchive

    Create a symbolic link (also symlink or soft link) in Linux - Ansible module file

    Create a hard link in Linux - Ansible module file

    Mount a Windows share in Linux SMB/CIFS - Ansible module mount

    Mount an NFS share in Linux - Ansible module mount

    Concatenate multiple files in a specific order - Ansible module template and YAML

    Backup With Rsync - Local to Remote - Ansible module synchronize

    Ansible For Linux User Management

    Ansible create a user account

    Ansible remove user account

    Ansible change user password

    Ansible disable user account

    Ansible enable user account

    Ansible user password expiration

    Ansible creates a group

    Ansible deletes a group account

    Ansible changes the User Primary Group on Linux

    Ansible adds a user to a secondary group(s)

    Ansible Playbook Code interact with Web Services API

    Submit a GET request to a REST API endpoint - Interact with web services - Ansible module uri

    Token-Based Authentication in REST API - Interact with web-service - Ansible module uri - Authentication request using the REST API token

    Ansible For Containers

    Ansible install Docker in Debian-like systems

    Ansible install Docker in RedHat-like systems

    Install Docker in Windows-like systems - Ansible module win_chocolatey

    Install Red Hat CodeReady Containers to run OpenShift 4 in macOS

    Create Kubernetes K8s or OpenShift OCP namespace project - Ansible module k8s

    Install Zoom flatpak in Debian-like systems - Ansible module flatpak

    Install Zoom flatpak in RedHat-like systems - Ansible module flatpak

    Update Zoom flatpak(s) in Linux systems - Ansible module command

    Install Spotify snap in Debian-like systems - Ansible module snap

    Install Spotify snap in RedHat-like systems - Ansible module snap

    Deploy Apache Web Server in a Docker Container for Debian-like systems - Ansible modules docker_image and docker_container

    Deploy Apache Web Server in a Podman Container for RedHat-like systems - Ansible modules podman_image and podman_container

    Ansible For Linux Security

    Set sysctl kernel parameters - Ansible module sysctl

    Load and Unload Kernel Modules in Linux - Ansible module modprobe

    Set the SELinux Policy States and Modes on Linux - Ansible module selinux

    Configure Kernel Parameters in RedHat-like Linux systems - Ansible system role

    Enable or Disable SELinux Boolean on Linux - Ansible module seboolean

    Enable or Disable Permissive Domain in SELinux policy on Linux - Ansible module selinux_permissive

    Vulnerability Scanner/Detector Log4Shell Remote Code Execution Log4j (CVE-2021–44228) — Ansible log4j-cve-2021–44228

    Ansible Playbook Code for RedHat-like systems

    Register a system with Red Hat Subscription-Manager - Ansible module redhat_subscription

    Install a package in RedHat like systems - Ansible module yum

    Rolling Update RedHat like systems - Ansible module yum

    Open firewall ports in RedHat like systems - Ansible module firewalld

    Install Google Chrome in RedHat-like systems - Ansible module rpm_key, yum_repos

    Install Microsoft Edge in RedHat-like systems - Ansible module rpm_key, yum_repository and yum

    NFS Server - Export an NFS Share in RedHat-like systems: RHEL, CentOS, CentOS Stream, Fedora - Ansible modules yum, file, lineinfile, command, firewalld, service

    Deploy a web server apache httpd on RedHat-like systems - Ansible modules yum, copy, service firewalld

    Deploy a proxy server squid on RedHat-like systems - Ansible modules yum, template, service and firewalld

    Deploy a web server apache httpd virtualhost on RedHat-like systems - Ansible modules yum, file, copy, template, service and firewalld

    Ansible Playbook Code for Debian-like systems

    Install a package in Debian like systems - Ansible module apt

    Rolling Update Debian-like systems - Ansible module apt

    Open firewall ports in Debian like systems - Ansible module ufw

    Install Google Chrome in Debian-like systems - Ansible module apt_key, apt_repos

    Install Google Chrome in Debian-like systems - Ansible module apt_key, apt_repos

    Deploy a web server apache httpd on Debian-like systems - Ansible modules apt, copy, service and ufw

    Deploy a web server apache httpd virtual host on Debian-like systems - Ansible modules apt, file, copy, template, command, ufw and service

    Ansible Playbook Code for Suse-like systems

    Install a package in Suse-like systems - Ansible module zypper

    Install Google Chrome in Suse-like systems - Ansible module rpm_key, zypper_repo

    Ansible Troubleshooting The Most Common Errors

    Ansible troubleshooting - connection failed

    Ansible troubleshooting - macOS fork error

    Ansible troubleshooting - indentation error

    Ansible troubleshooting - syntax error

    Ansible troubleshooting - undefined variable

    Ansible troubleshooting - invalid argument

    Ansible troubleshooting - privilege escalation error

    Ansible troubleshooting - missing sudo password and incorrect sudo password

    Ansible troubleshooting - missing module parameter

    Ansible troubleshooting - failure downloading

    Ansible troubleshooting - chgrp failed

    Ansible troubleshooting - not a valid attribute for a Play error

    Ansible troubleshooting - fatal template error while templating string

    Ansible troubleshooting - PowerShell incompatible with the sudo become plugin

    Ansible troubleshooting - passwordless account

    Ansible troubleshooting - user module password_expiry_min bug

    Ansible troubleshooting - Windows 10 Error 0x80370102 WSL: Windows Subsystem for Linux

    Ansible troubleshooting - Windows 11 Error 0x80370102 WSL: Windows Subsystem for Linux

    Ansible troubleshooting - urlopen error

    Ansible troubleshooting - destination does not exist

    Ansible troubleshooting - role not found error

    Ansible troubleshooting - permission denied Errno 13

    Ansible troubleshooting - VARIABLE IS NOT DEFINED! ansible_hostname

    Ansible troubleshooting - This command has to be run under the root user

    Thank you

    Introduction

    This book provides an introduction to the Ansible language.

    Ansible is a popular open source IT automation technology for scripting applications in a wide variety of domains.

    It is free, portable, powerful, and remarkably easy and fun to use.

    This book is a tool to learn the Ansible automation technology with some real-life examples.

    Whenever you are new to automation or a profession automation engineer, this book’s goal is to bring you quickly up to speed on the fundamentals of the core Ansible language.

    Every successful IT department needs automation nowadays for bare metal servers, virtual machines, cloud providers, containers, and edge computing. Automate your IT journey with Ansible automation technology.

    I’m going to teach you example by example how to accomplish the most common System Administrator tasks.

    You are going to start with the installation of Ansible in Red Hat Enterprise Linux, Ubuntu, and macOS using the most command package manager and archives.

    Each of the 100+ lessons summarizes a module: from the most important parameter to some live demo of code and real-life usage. Each code is battle proved in the real life. Console interaction and verification are included in every video. A mundane activity like creating a text file, extracting and archiving, fetching a repository using HTTPS or SSH connections could be automated with some lines of code and these are only some of the long lists included in the course.

    There are some Ansible codes usable in all the Linux systems, some specific for RedHat-like, Debian-like, and Windows systems.

    The 20+ Ansible troubleshooting lesson teaches you how to read the error message, how to reproduce, and the process of troubleshooting and resolution.

    Are you ready to automate your day with Ansible?

    Whois Luca Berton

    I’m Luca Berton and we’re going to have a lot of fun together.

    First of all, let me introduce myself.

    I’ve been Ansible Technical Support Engineer of Red Hat, based in the Czech Republic, even if I’m Italian.

    I’ve been more than 15 years System Administration, working with infrastructure, either on-premise or on the major cloud providers.

    I’m an enthusiast of the Open Source support the community by sharing my knowledge in different events of public access.

    I’m also a co-founder of my hometown Linux Users Group, visited by Richard Stallman, the founder of the Free Software Movement.

    I consider myself a lazy person so I always try new ways to automate the repetitive task of my work.

    After years of Perl, Bash, and python scripting I landed in Ansible technology. I took the certification and worked for more than a year with the Ansible Engineer Team.

    I consider Ansible the best infrastructure automation technology nowadays, it’s human-readable, the learning curve is accessible, and very requested by the recruiters in the market.

    This ultimate guide contains all of the obvious and not-so-obvious solutions using Ansible automation.

    In every lesson of this course, I’m going to share with you one specific use case, the possible solution, the code, the execution, and the verification of the target system.

    All these solutions are battle-tested and used by me in my everyday automation.

    You could easily jump between lessons and review again all the times that you need.

    Awards & Recognition

    2022

    Ansible Anwendertreffen - From Zero to Hero: How to build the Ansible Pilot Community - by Luca Berton (Red Hat CZ) 15:15 - 16:00 15 Feb 2022

    Red Hat Ansible Playbook included in RHSB-2021-009 Log4Shell - Remote Code Execution - log4j (CVE-2021-44228) 12 Jan 2022

    AWS Tip Set sysctl kernel parameters — Ansible module sysctl 12 Jan 2022

    The Ansible Bullhorn #41 - A Newsletter for the Ansible Developer Community 7 Jan 2022

    2021

    The Ansible Bullhorn #34 - A Newsletter for the Ansible Developer Community 17 Sep 2021

    The course is going to keep track of the evolution of the Ansible technology adding more content whenever is needed.


    Are you ready to have fun?

    Ansible For Beginners With Examples

    In this chapter you’re going to discover the Ansible Basics, Architecture and Terminology.

    What is Ansible

    In this chapter, I’ll explain to you what is Ansible and why it is so powerful for your IT department.

    Ansible

    Infrastructure Automation tool

    Open Source infrastructure as code

    First of all, let’s begin our adventure with the fabulous Open Source technology named Ansible. It is classified as an Infrastructure Automation tool, so you could automate your System Administrator tasks very easily. Infrastructure as code is the process of managing and provisioning computer data centers through machine-readable definition files, rather than physical hardware configuration or interactive configuration tools. Ansible follows the DevOps principles. With Ansible you could deploy your infrastructure as code on-premise and on the most well-known public cloud provider.

    Ansible three Use Cases

    Provision

    Config management

    Application deployment

    The three main use cases of Ansible are provision, configuration management, and app deployment. But after touching the technology I’m sure you could invent some more ways to use it!

    Provisioning

    The process of setting up the IT infrastructure

    Let’s start talking about provisioning: all the System Administrator know how important is to manage a uniform fleet of machines. Some people still rely on software to create workstation images. But there is a drawback, with imaging technology you’re only taking a snapshot in time of the machine. So every time you need to reinstall software because of the modern key activation systems or update manually to the latest security patches. Ansible is very powerful to automate this process being able to create a more smooth process.

    Configuration management

    The process for maintaining systems and software in a desired and consistent state

    The second key use case is configuration management: maintain up-to-date and in a consistent way all your fleet, coordinating rolling updates and scheduling downtime. With Ansible you could verify the status of your managed hosts and take action in a small group of them. A huge variety of modules is available for the most common use cases. Not to mention the common use case to check the compliance of your fleet to some international standard and apply resolution plans.

    Application deployment

    The process to publish your software between testing, staging and production environment

    The third key use case where Ansible is useful is Application deployment. It could automate the continuous integration / continuous delivery workflow pipeline of your web application for example. Your DevOps team will be delighted!.

    Ansible in DevOps

    Ansible is used to apply the DevOps principles in worldwide organizations. Let me quickly summarize.

    DevOps is a set of practices that combines software development (Dev) and IT operations (Ops). As DevOps is intended to be a cross-functional mode of working, those who practice the methodology use different sets of tools referred to as toolchains rather than a single one. These toolchains are expected to fit into one or more of the following categories, reflective of key aspects of the development and delivery process. The seven categories:

    Code: code development and review, source code management tools, code merging.

    Build: continuous integration tools, build status.

    Test: continuous testing tools that provide quick and timely feedback on business risks.

    Release: artifact repository, application pre-deployment staging.

    Deploy: change management, release approvals, release automation.

    Operate: infrastructure configuration and management, infrastructure as code tools.

    Monitor: applications performance monitoring, end-user experience.

    Four key tenets of Ansible

    1. Declarative

    You declare what you want rather than how to get to.

    2. Agentless

    You don’t need to install an agent. It takes advantage of OpenSSH.

    3. Idempotent

    An operation could be run multiple times without changing beyond the initial operation.

    4. Community driven

    Published in Ansible Galaxy as collections and roles.

    The four key tenets of ansible are: declarative, agentless, idempotent, and community-driven. With declarative it means that you could use in a way very similar to a programming language apply sequencing, selection, and iteration to the code flow. With agentless it means that you don’t need to install and update any agents on the target machine, it uses the SSH connection and python interpreter. The language itself is idempotent, which means that the code will check a precise status on the managed machine. It means that for example the first time your code will change something, the following runs it only verify that nothing changed and move forward. The last tenet is community-driven, which means that exists a public archive called Ansible Galaxy where you could download the code made by other open source contributors. This code is organized in roles and collections, but we’ll see it in the future.

    Ansible six values

    Simple

    YAML human readable automation.

    Powerful

    Configuration management, workflow orchestration, application deployment.

    Cross-platform

    Agentless support for all major OS, physical, virtual, cloud and network.

    Work with existing tools

    Homogenize existing environment.

    batteries included

    Come bundled with 750+ modules.

    Community powered

    Download \250k/months People \3500 contributors, 1200 users on IRC.

    Now let’s talk about the six values of Ansible. The first is that is simple: the code is written in YAML language, that is a human-readable data serialization language. It is well known and easy to learn, it is commonly used for configuration files and in applications where data is being stored or transmitted. Ansible is Powerful, it is battle-tested as Configuration management, workflow orchestration, application deployment. The third value is cross-platform by nature, the Agentless support for all major Operating Systems, physical, virtual, cloud, and network provider. Another value of Ansible is that it works with existing tools, it easy to homogenize the existing environment. The batteries included means that Ansible included bundled more than 750 modules to automate the most common tasks. The last value is that Ansible is community-powered", every month has more than 250000 downloads, an average of 3500 contributors, and more than 1200 users on IRC.

    Ansible history

    2012

    Developed by Michael DeHaan

    2015

    Acquired by Red Hat

    2016

    AnsibleFest events

    2020

    Red Hat Ansible Automation Platform 1.0

    2021

    Red Hat Ansible Automation Platform 2.1

    The main events in Ansible history are the following.

    The first release of Ansible was public on the 20th of February 2012. The Ansible tool was developed by Michael DeHaan. Ansible Inc., originally AnsibleWorks Inc., was the company set up to commercially support and sponsor the project.

    On the 16th of October 2015 Red Hat acquired Ansible Inc., and evaluate Ansible as a powerful IT automation solutions designed to help enterprises move toward friction less IT.

    AnsibleFest is an annual conference of the Ansible community of users, contributors since 2016 in London and the USA.

    Ansible & Ansible Tower & Ansible Automation Platform

    Ansible

    Community driven project fast-moving innovations Open Source but only command line tools.

    Red Hat Ansible Tower / Ansible Automation Platform

    It is a framework designed by RedHat. It provides a web UI to manage your infrastructure.

    Ansible is a community-driven project with fast-moving innovations Open Source but only command-line tools.

    Enterprise needs more services and some stable releases. For example, they need an SLA for support. Red Hat offers this service to companies namely under the Ansible Tower umbrella, now re branded as Ansible Automation Platform.

    Ansible Tower is a REST API, web service, and web-based console designed to make Ansible more usable for IT teams with members of different technical proficiency and skill-sets. It is a hub for automation tasks. The tower is a commercial product supported by Red Hat Inc. but derived from AWX upstream project, which is open source since September 2017.

    Red Hat maintains also Ansible Engine. With Ansible Engine, organizations can access the tools and innovations available from the underlying Ansible technology in a hardened, enterprise-grade manner. Ansible Engine is developed by Red Hat with the explicit intent of being used as an enterprise IT platform.

    Getting Started

    In this chapter, I’ll explain you how to move the firsts steps with Ansible technology. How to connect to the managed hosts and how to execute some simple tasks using the command line.

    Ansible architecture

    Let’s Begin a talking about Ansible architecture. The node where Ansible is actually installed is called control node and it manages all your fleet of nodes. The controlled node on the other hand is called managed node. The target nodes could be Linux, Mac, Windows and several network equipment. Each target has some specificity like different Linux distribution and module usage. We will discuss of the specificity the in the next sections.

    Connection with managed nodes

    The connection between control node and managed nodes is managed by SSH protocol without any requirement of specific client on the target machine. Other competitor require a client software often called agent. With SSH connection the only requirements are a username and a certificate to access the target machine. There are some way to automate also this first script step. After completing SSH connection another requirement is python interpreter, witch come out-of-the-box for modern operating systems. By default Ansible uses SFTP to transfer files but you could switch to SCP in configuration. The Windows target could be connected using WinRM technology and uses PowerShell as interpreter.

    Create a basic inventory

    /etc/ansible/hosts

    1 host1.example.com

    default inventory file /etc/ansible/hosts

    host1.example.com is a managed host

    The list of managed hosts is stored in /etc/ansible/hosts. In this example it contain only one host named host1.example.com.

    Run your first Ansible command

    1 $ ansible all -m ping 2 host1.example.org | SUCCESS => { 3     ansible_facts: { 4         discovered_interpreter_python: /usr/bin/python 5     }, 6     changed: false, 7     ping: pong 8 }

    ping module executed on all hosts

    host1.example.com replied with a success code

    Now we’re ready to run your first Ansible command. The Ansible command is called module in Ansible slang. The first line executed Ansible ping module on all hosts. The response is a pong. Please note that this means that Ansible is able to connect with SSH username, identify using public key and execute the local python executer. So it’s completely different from any ping in networking.

    Run ad-hoc command on Ansible

    1 $ ansible all -a /bin/echo hello 2 host1.example.org | CHANGED | rc=0 >> 3 hello

    /bin/echo hello command executed on all hosts

    host1.example.com replied with a changed code and print hello on standard output

    Ansible could also execute some command on the target host and report the status on the console of control node. In this example /bin/echo hello command was executed on all hosts. host1.example.com replied with a changed code and print hello on standard output. Please note that you would receive a changed state every time you run a command on the remote machine.

    Run ad-hoc command with privilege escalation on Ansible

    1 $ ansible all -m ping -u devops --become 2 host1.example.org | SUCCESS => { 3     ansible_facts: { 4         discovered_interpreter_python: /usr/bin/python 5     }, 6     changed: false, 7     ping: pong 8 }

    ping module executed on all host as user root after login with user devops

    host1.example.com replied with a changed code and print hello on standard output

    In this example I run the ping module against all host as user root after login with user devops. host1.example.com replied with a changed code and print hello on standard output.

    Recap

    In this module we learned the basic concept of Ansible architecture, how to write the list of managed hosts and how to execute some simple commands against it.

    Inventory

    In this chapter, I’ll explain to you what is an Ansible inventory, why do you need, the different types how to edit and use it in your day to day journey.

    1 An inventory is the set of hosts Ansible could work again\ 2 st. 3 They could be categorized as groups/patterns.

    The list of multiple hosts managed by Ansible is called inventory. It is fundamentally the list of nodes or hosts in your infrastructure at the same time, using a list or group of lists known as inventory. You could organize your inventory with groups or patterns to select the hosts or group you want Ansible to run against.

    all keyword

    1 the keyword all includes all hosts of the inventory, exce\ 2 pt localhost

    The special keyword all include all the hosts of the inventory used. It will be very useful in the following lessons. The only exception is localhost that you need to specify.

    Simple INI inventory

    ./ini_simple_inventory

    1 one.example.com 2 3 [webservers] 4 two.example.com 5 three.example.com

    file name: ini_simple_inventory

    one.example.com is ungrouped

    two.example.com and three.example.com are grouped as webserver

    The simplest inventory type is the INI inventory, by the type of the file. The default location is /etc/ansible/hosts but you could use your customized with -i parameter. In this example host one.example.com is ungrouped and two.example.com and three.example.com are grouped as webserver.

    Simple YAML inventory

    ./simple_yaml_inventory.yml

    1 --- 2 all: 3   hosts: 4     one.example.com: 5   children: 6     webservers: 7       hosts: 8         two.example.com: 9         three.example.com:

    file name: inventory.yml

    one.example.com is ungrouped

    two.example.com and three.example.com are grouped as webserver

    You could express the same inventory using YAML syntax In this example In this example host one.example.com is ungrouped and two.example.com and three.example.com are grouped as webserver.

    Add ranges of hosts

    ./ini_range_inventory

    1 [webservers] 2 www[01:99].example.com 3 4 [databases] 5 db-[a-f].example.com

    webservers group contains all hosts from www01.example.com to www99.example.com

    Databases group contains all hosts from db-a.example.com to db-f.example.com,

    Group members could be defined also using ranges by numbers or letters. In the range by numbers you could also specify a stride the increment between a sequence of number. In this INI example webservers group contains all hosts from www01.example.com to www99.example.com. databases group contains all hosts from db-a.example.com to db-f.example.com.

    Host in multiple groups

    ./ini_groupsmultiple_inventory

    1 one.example.com 2 3 [webservers] 4 two.example.com 5 three.example.com 6 7 [prod] 8 two.example.com 9 10 [dev] 11 three.example.com

    hosts two.example.com and three.example.com are present in multiple groups

    Hosts could be present in multiple groups. In this INI example hosts two.example.com and three.example.com are grouped as webserver. two.example.com is present in webserver as well as prod group.

    three.example.com is present in webserver and dev group.

    Host variables

    ./ini_hostinventory

    1 [webservers] 2 localhost  ansible_connection=local 3 one.example.com ansible_connection=ssh ansible_user=devops 4 two.example.com ansible_connection=ssh ansible_user=ansib\ 5 le

    Customization of ansible_connection and ansible_user variables

    In inventory you might would like to store variable values that relate to a specific host or group. This example scenario is common because it defines different connection with different hosts. For example to use local connection for the localhost and ssh, default, for all the other hosts. For each hosts you could customize also the login user devops for one.example.com and ansible for two.example.com".

    Group variables

    ./ini_groupsvariables_inventory

    1 [webservers] 2 one.example.com 3 two.example.com 4 5 [webservers:vars] 6 ntp_server=europe.pool.ntp.org

    ./inventory.yml

    1 --- 2 webservers: 3   hosts: 4     two.example.com: 5     three.example.com: 6   vars: 7     ntp_server: europe.pool.ntp.org

    As well as per single host is possible to define group variables. This two inventory files in the example (INI and YAML format) the variables ntp_server has assigned the value europe.pool.ntp.org for all the hosts of the group.

    Inheriting variable values

    ./ini_variableinheriting_inventory

    1 [asia] 2 host1.example.com 3 4 [europe] 5 host2.example.com 6 7 [webserver:children] 8 asia 9 europe 10 11 [webservers:vars] 12 ntp_server=europe.pool.ntp.org

    ./variableinheriting_inventory.yml

    1 --- 2 children: 3   webservers: 4     children: 5       asia: 6         hosts: 7           host1.example.com: 8       europe: 9         hosts: 10           host2.example.com: 11     vars: 12       ntp_server: europe.pool.ntp.org

    Hosts and group could be combined together. In this example the group webserver has two members asia and europe. This two elements are defined as a single host host1.example.com and host2.example.com, respectively, but could contains more hosts as well. ntp_server variables is defined at webservers level. So in the end ntp_server variable is available for webserver, asia and europe group. ntp_server variable is available as well in host1.example.com and host2.example.com hosts.

    Use multiple inventory sources

    1 $ ansible-playbook playbook.yml -i production -i developm\ 2 ent

    Execute ansible playbook named playbook.yml against production and development

    Is possible to use multiple inventory files for each execution. In this example is going to be executed ansible playbook named playbook.yml against production and development inventories.

    localhost inventory

    ./ini_local_inventory

    1 localhost ansible_connection=local

    file name: inventory

    /etc/ansible/hosts default

    One special case in inventory is with localhost. You need to specify the connection type as local, otherwise Ansible presume to use the default SSH connection.

    Recap

    Now you know more about Ansible INI and YAML inventory files, host and group variable.

    Playbook

    In this chapter, I’ll explain to you what is an Ansible Playbook and why do you need. We’ll cover how to start with a simple playbook, from the basic syntax and how to add more tasks.

    1 A playbook is a set of play to be executed against an inv\ 2 entory.

    YAML syntax

    1 # This is a YAML comment 2 some data # This is also a YAML comment 3 4 this is a string 5 'this is another string' 6 this is yet another a string 7 8 with_newlines: | 9 Example Company 10 123 Main Street 11 New York, NY 10001 12 13 without_newlines: > 14 This is an example 15 of a long string, 16 that will become 17 a single sentence. 18 19 yaml_dictionary: {name1: value1, name2: value2} 20 21 yaml_list1: 22 - value1 23 - value2 24 yaml_list2: [value1, value2]

    Every playbook is based on YAML syntax so the file is easy and human readable. YAML is a text format and you could easy recognize by the presence of the three dash symbols at the beginning and three dots in the end. The three dots are not mandatory so a lot of people simply omit them. This file type is very sensitive to spacing between elements. It’s strictly important that elements of the same level are in the same indentation, despite some programming languages. You could use the symbol # for comments, even on the lines with some previous code. String are very important and you could specify directly or with single or double quote. I recommend you to use a double quote as a general rule. Using the pipe and major statement you could define multi-line strings. The first statement will keep the newlines, the second not. Others useful data structures are dictionaries and lists that you could see in action in the grayboard.

    helloworld.yml

    helloworld.yml

    1 --- 2 - name: Hello World sample 3   hosts: all 4   tasks: 5     - name: Hello message 6       ansible.builtin.debug: 7         msg: Hello World! 8 ...

    1 file name: helloworld.yml 2 Name of the playbook 3 Hosts of execution 4 List of tasks 5 One task named Hello message 6 Module ansible.builtin.debug 7 Argument msg of module debug

    This is the output of the execution of the helloworld.yml. I’d like you to note the command used is ansible-playbook. The first parameter is the inventory file and the second is the playbook.

    In this execution the play is executed against the host1.example.com node. The output is very clear of the step by step execution. When the command is successful the output is highlighted with green color. A warning will be presented in orange and an error in red. The most attent of you have noticed an extra task executed called Gathering Facts that is performed by Ansible to acquire some information of the managed node. We’ll discuss more about facts gathering in the following lesson. Try by yourself the execution of this code and become confident with this output summary. It will be very useful. Two tasks are being executed.

    Tip1: ansible-playbook –check option

    1 $ ansible-playbook -i inventory  --check  helloworld.yml 2 PLAY [Hello World sample] *******************************\ 3 *********************************************************\ 4 *********** 5 TASK [Gathering Facts] **********************************\ 6 *********************************************************\ 7 ******** 8 ok: [host1.example.com] 9 TASK [Hello message] ************************************\ 10 *********************************************************\ 11 ****** 12 ok: [host1.example.com] => { 13     msg: Hello World! 14 } 15 PLAY RECAP **********************************************\ 16 ***************************************************** 17 host1.example.com      : ok=2    changed=0    unreachabl\ 18 e=0    failed=0    skipped=1    rescued=0    ignored=0

    A very useful option of –check for ansible-playbook command. This option to perform a dry run on the playbook execution. This causes Ansible to report what changes would have occurred if the playbook were executed, but does not make any actual changes to managed hosts.

    Tip2: debug day-to-day usage

    helloworld_debug.yml

    1 --- 2 - name: Hello World sample 3   hosts: all 4   tasks: 5     - name: Hello message 6       debug: 7         msg: Hello World! 8         verbosity: 2 9 ...

    1 file name: helloworld_debug.yml 2 Name of the playbook 3 Hosts of execution 4 List of tasks 5 One task named Hello message 6 Module debug 7 Argument msg of module debug 8 Argument varbosity is 2

    This tip allow you to keep the debug code in your playbook and enable the execution only when you need. For example the message is printed only when Ansible is invoked with output level two.

    helloworld_debug.yml - execution - part 1

    1 ansible-playbook -i inventory helloworld_debug.yml 2 PLAY [Hello World sample] *******************************\ 3 *********************************************************\ 4 *********** 5 6 TASK [Gathering Facts] **********************************\ 7 *********************************************************\ 8 ******** 9 ok: [host1.example.com] 10 11 TASK [Hello message] ************************************\ 12 *********************************************************\ 13 ****** 14 skipping: [host1.example.com] 15 16 PLAY RECAP **********************************************\ 17 ***************************************************** 18 host1.example.com      : ok=1    changed=0    unreachabl\ 19 e=0    failed=0    skipped=1    rescued=0    ignored=0

    This is the output of helloworld_debug.yml when is executed normally, which means not in debug mode. As you could notice the hello message is skipped.

    helloworld_debug.yml - execution - part 2

    1 $ ansible-playbook -i inventory -vv helloworld_debug.yml 2 PLAY [Hello World sample] *******************************\ 3 *********************************************************\ 4 *********** 5 TASK [Gathering Facts] **********************************\ 6 *********************************************************\ 7 ******** 8 ok: [host1.example.com] 9 TASK [Hello message] ************************************\ 10 *********************************************************\ 11 ****** 12 ok: [host1.example.com] => { 13     msg: Hello World! 14 } 15 PLAY RECAP **********************************************\ 16 ***************************************************** 17 host1.example.com      : ok=2    changed=0    unreachabl\ 18 e=0    failed=0    skipped=1    rescued=0    ignored=0

    This is the output of helloworld_debug.yml when is executed in debug level two mode, please notice the two V in the command line. As you could notice the hello message is printed.

    Idempotency

    1 idempotency 2 modules check the desired final state has already been ac\ 3 hieved, otherwise apply

    One important characteristics of most of Ansible modules is to be idempotent. It means that before executing any actions on the target node, the module is going to check the actual status. If the actual status match the desired once, no action is going to be performed. If the current status divert from the expected once an action will take place. Please note that if you execute another time the playbook the desired status will be found and no further actions will be performed. This property is called idempotency and you’re young to take advantage of it.

    multipleplays.yml

    1 --- 2 - name: first play 3   hosts: web.example.com 4   tasks: 5     - name: first task 6       ansible.builtin.yum: 7         name: httpd 8         status: present 9     - name: second task 10       ansible.builtin.service: 11         name: httpd 12         enabled: true 13 - name: second play 14   hosts: database.example.com 15   tasks: 16     - name: first task 17       ansible.builtin.service: 18         name: mariadb 19         enabled: true

    file name: multipleplays.yml

    Two plays inside to be execute against of web.example.com and database.example.com

    The multipleplays.yml playbook contains two plays. The first play is executed against the web.example.com host and install and apache web server and enable on boot. The second play is going to be executed against database.example.com and enable on boot the execution of madiadb database management system. As you could see using multiple play is very powerful to execute different tasks in different hosts. Now the definition of playbook make more sense.

    privilege_escalation.yml

    1 --- 2 - name: install httpd 3   hosts: web.example.com 4   become: true 5   become_method: sudo 6   become_user: root 7   tasks: 8     - name: install httpd 9       ansible.builtin.yum: 10         name: httpd 11         status: present

    privilege_escalation.yml

    become specify that privilege escalation is necessary

    become_method specify the escalation method

    become_user specify the destination user (default root)

    Some action need to be taken by a user with administrative power. In Linux typically is the root user. Some distribution allow the privilege escalation using sudo command using the wheel group. In this example I’m going to install a software so I need the privilege escalation. The yum module need to perform some action on the managed node. In playbook when is not necessary you could disable.

    Most common Ansible modules

    Files modules

    copy: copy a local file to the managed host

    fetch: copy files from remote nodes to local

    file: set permissions and other properties of files

    lineinfile: ensure a particular line is or is not in a file

    synchronize: synchronize content using rsync

    Software package modules

    package: manage packages using autodetected package manager native to the operating system

    yum: manage packages using the YUM package manager

    apt: manage packages using the APT package manager

    dnf: manage packages using the DNF package manager

    gem: manage Ruby gems

    pip: manage Python packages from PyPI

    System modules

    firewalld: manage arbitrary ports and services using firewalld

    reboot: reboot a machine

    service: manage services

    user: add, remove, and manage user accounts

    Net tools modules

    get_url: Download files in HTTP, HTTPS, and FTP

    nmcli: Manage networking

    uri: Interact with web services

    Recap

    In this module we put the foundation of the following operation on Ansible Playbook. Keep going and soon you will be able to automate all your System Administrator tasks.

    Variables

    In this chapter, I’ll explain to you what are Ansible variables, why do you need, the different types how to edit and use it in your day to day journey.

    1 variable store dynamic value for a given environment.

    In your Playbook is a good practice to use Variables to store all the dynamic value that you need. Editing variables you could reuse your code in the future only parameterize accordingly your business needs.

    Not permitted variables names

    no white spaces my var

    no dots my.var

    don’t starts with number 1stvar

    don’t contain special character myvar$1

    Ansible allow all the combination of letters and numbers in variables names. If you plan to use numbers be aware that you can’t use at the beginning, but this is a general rule in information technology world.

    The four main limitations in variable names are: no white spaces are allowed, no dots, don’t starts with numbers, don’t contain special characters. So on the right you see some example of invalid variables names.

    variableprint.yml

    ./variableprint.yml

    1 --- 2 - name: Variable print sample 3   hosts: all 4   vars: 5     fruit: apple 6   tasks: 7     - name: Print variable 8       ansible.builtin.debug: 9         msg: Print the value of variable {{ fruit }}

    1 file name: variableprint.yml 2 Name

    Enjoying the preview?
    Page 1 of 1