ANSIBLE

Advantages of Ansible

Ansible is very easy to learn and allows you to get up and running with automation more quickly than other tools. Ansible is agentless, so you don’t have to install and maintain an Ansible client on your managed nodes. This dramatically simplifies the management of Ansible updates.

Drawbacks of Ansible

Ansible, of course, is not a perfect tool. If an SSH connection is interrupted partway through a playbook run, that node could end up in a partially configured state. Ansible also has a reputation for being slow and may require additional performance tuning to meet your requirements.

 

  1. Setup Tool

Installing Ansible on Ubuntu

You can install Ansible on any *nix-based operating system. One of the most popular choices out there is Ubuntu. Let’s kick off this tutorial and go through a walkthrough on how to make it happen.

If you’d like to set up Ansible on Ubuntu, this section is going to assume you have an Ubuntu 18+ machine with Python2 or higher installed. This tutorial will be using Ubuntu 18.04.5 LTS with Python3.

  1. Connect to your soon-to-be Ansible controller on an Ubuntu host with your favorite SSH client.
  2. Ansible is stored as a package that can be downloaded and installed via the apt package manager. To ensure apt can find the proper source and download any dependent packages run apt update.

sudo apt update

The apt or apt-get command installs the packages from apt software repositories configured in Ubuntu.

  1. Continue preparing apt to download and install Ansible by installing the software-properties-common package. sudo apt install software-properties-common

sudo apt install software-properties-common

Installing the package using apt command

  1. Next, add the ansible/ansible personal package archive (PPA) as an apt repository. This repository is managed by Red Hat, not by Ubuntu sources, so you must add it manually.

sudo apt-add-repository –yes –update ppa:ansible/ansible

Addition of ansible PPA repository

  1. Now, install the ansible package by running the apt install command

sudo apt install ansible

  1. When complete, confirm Ansible is installed by running the ansible –version command. If all is well ansible –version

ansible –version

Checking the Ansible version

Installing Ansible on RHEL

Ubuntu isn’t the only operating system Ansible supports. Red Hat Enterprise Linux (RHEL) or CentOS are also common options. Let’s start with RHEL.

If you plan to follow this section, ensure you have an RHEL release 8+ host (this tutorial will use RHEL 8.3 (Ootpa).

  1. Connect to your RHEL host via SSH with your favorite SSH client.
  2. Install the python3-pip and python3 package with dnf. Ansible works with Python2, but this tutorial will be using Python3 because Python2 is soon to be considered legacy.

sudo dnf install python3 python3-pip -y

Installing the python3 and python3-pip

  1. Install the Extra Packages for Enterprise Linux (EPEL) repository. The EPEL repository contains various system packages including the Ansible package which you will install in the next step.

sudo dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm

Addition of EPEL repository

  1. Once you’ve installed the repository, install the Ansible package by referencing the required EPEL repository and the package’s name (ansible). The dnf utility will automatically download the latest version of Ansible.

sudo dnf install  —enablerepo epel-playground  ansible

  1. Now, check to ensure Ansible has been installed successfully by runnin

Checking the Ansible version

Installing Ansible on CentOS

Rounding out the *nix hosts, let’s end with setting up Ansible on CentOS.

If you plan to follow this section, ensure you have a CentOS 7+ host with Python2 or higher installed (this tutorial will use CentOS 7.9.2009 Core).

  1. Connect to your CentOS host via SSH with your favorite SSH client.
  2. Install the Extra Packages for Enterprise Linux (EPEL) repository. The EPEL repository contains various system packages, including the Ansible package, which you will install in the next step.

# Installing the epel-release package using the yum command yum install epel-release

yum install epel-release

The yum command installs and manages software by using the official Red Hat software repositories, as well as other third-party repositories.

Installing the epel-release package using the yum command

  1. Once the repository is complete, install the Ansible package.

sudo yum install ansible

Installation of Ansible package

  1. Now, confirm Ansible is installed by running ansible –version.

Checking the Ansible Version

Installing Ansible on macOS

So far, you have learned how to set up Ansible on various Linux distros. Let’s finish out this tutorial by learning how to install Ansible on a Mac.

This section of the tutorial will focus on the popular macOS package manager called Homebrew. Homebrew is the easiest way to install Ansible on macOS. This tutorial will be using Homebrew v3.0.7 on macOS Catalina.

If you’d like to learn how to install Ansible via the popular Python package manager pip, check out the Ansible pip package.

To install on macOS:

  1. Open up the Apple Terminal.
  2. Run the following command to invoke Homebrew to download and install Ansible on your Mac.

brew install ansible

  1. Once complete, verify Ansible is installed by running ansible –version.

$ ansible –version

ansible 2.7.5

  config file = None

  configured module search path = [‘/Users/shanky/.ansible/plugins/modules’, ‘/usr/share/ansible/plugins/modules’]

  ansible python module location = /usr/local/Cellar/ansible/2.7.5/libexec/lib/python3.7/site-packages/ansible

  executable location = /usr/local/bin/ansible

  python version = 3.7.2 (default, April 13 2021, 07:35:52) [Clang 10.0.0 (clang-1000.11.45.5)]

Testing Out Ansible by Running Ad-Hoc Commands

Now that Ansible is installed, it’s not doing much good unless you actually use it! One of the easiest ways to get started with Ansible is to learn about ad hoc commands. Ad hoc commands are one-off usually single-line commands that the Ansible invokes on remote computers (or on the Ansible host in this example).

Related:Running ad-hoc Commands on Windows Hosts

Run an ad-hoc command on your operating system of choice by using the -m switch. The -m switch specifies an Ansible module that contains various functionality.

One of the simplest Ansible modules is the ping module. This module tests connectivity between the Ansible controller and a host. If you don’t have any remote hosts available, provide the name of the Ansible controller itself (localhost) to run the ping module against.

ansible localhost  -m ping

If successful, you should see green output indicating success!

Running the ansible ad hoc ping module

  1. Using Tool

Getting Started

Now that you have read the installation guide and installed Ansible on a control node, you are ready to learn how Ansible works. A basic Ansible command or playbook:

  • selects machines to execute against from inventory
  • connects to those machines (or network devices, or other managed nodes), usually over SSH
  • copies one or more modules to the remote machines and starts execution there

Ansible can do much more, but you should understand the most common use case before exploring all the powerful configuration, deployment, and orchestration features of Ansible. This page illustrates the basic process with a simple inventory and an ad hoc command. Once you understand how Ansible works, you can read more details about ad hoc commands, organize your infrastructure with inventory, and harness the full power of Ansible with playbooks.

Selecting machines from inventory

Ansible reads information about which machines you want to manage from your inventory. Although you can pass an IP address to an ad hoc command, you need inventory to take advantage of the full flexibility and repeatability of Ansible.

Action: create a basic inventory

For this basic inventory, edit (or create) /etc/ansible/hosts and add a few remote systems to it. For this example, use either IP addresses or FQDNs:

192.0.2.50

aserver.example.org

bserver.example.org

 

Beyond the basics

Your inventory can store much more than IPs and FQDNs. You can create aliases, set variable values for a single host with host vars, or set variable values for multiple hosts with group vars.

Connecting to remote nodes

Ansible communicates with remote machines over the SSH protocol. By default, Ansible uses native OpenSSH and connects to remote machines using your current user name, just as SSH does.

Action: check your SSH connections

Confirm that you can connect using SSH to all the nodes in your inventory using the same username. If necessary, add your public SSH key to the authorized_keys file on those systems.

Beyond the basics

You can override the default remote user name in several ways, including:

  • passing the -u parameter at the command line
  • setting user information in your inventory file
  • setting user information in your configuration file
  • setting environment variables

See Controlling how Ansible behaves: precedence rules for details on the (sometimes unintuitive) precedence of each method of passing user information. You can read more about connections in Connection methods and details.

Copying and executing modules

Once it has connected, Ansible transfers the modules required by your command or playbook to the remote machine(s) for execution.

Action: run your first Ansible commands

Use the ping module to ping all the nodes in your inventory:

$ ansible all -m ping

 

You should see output for each host in your inventory, similar to this:

aserver.example.org | SUCCESS => {

    “ansible_facts”: {

        “discovered_interpreter_python”: “/usr/bin/python”

    },

    “changed”: false,

    “ping”: “pong”

}

 

You can use -u as one way to specify the user to connect as, by default Ansible uses SSH, which defaults to the ‘current user’.

Now run a live command on all of your nodes:

 

$ ansible all -a “/bin/echo hello”

 

You should see output for each host in your inventory, similar to this:

aserver.example.org | CHANGED | rc=0 >>

hello

 

Action: Run your first playbook

Playbooks are used to pull together tasks into reusable units.

Ansible does not store playbooks for you; they are simply YAML documents that you store and manage, passing them to Ansible to run as needed.

In a directory of your choice you can create your first playbook in a file called mytask.yml:

name: My task

  hosts: all

  tasks:

      name: Leaving a mark

       command: “touch /tmp/ansible_was_here”

 

You can run this command as follows:

$ ansible-playbook mytask.yaml

 

and may see output like this:

PLAY [My task] **************************************************************************************************************************

 

TASK [Gathering Facts] ******************************************************************************************************************

ok: [aserver.example.org]

ok: [aserver.example.org]

ok: [192.0.2.50]

fatal: [192.0.2.50]: UNREACHABLE! => {“changed”: false, “msg”: “Failed to connect to the host via ssh: ssh: connect to host 192.0.2.50 port 22: No route to host”, “unreachable”: true}

 

TASK [Leaving a mark] *******************************************************************************************************************

[WARNING]: Consider using the file module with state=touch rather than running ‘touch’.  If you need to use command because file is

insufficient you can add ‘warn: false’ to this command task or set ‘command_warnings=False’ in ansible.cfg to get rid of this message.

changed: [aserver.example.org]

changed: [bserver.example.org]

 

PLAY RECAP ******************************************************************************************************************************

aserver.example.org        : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

bserver.example.org        : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

192.0.2.50                 : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0

 

Read on to learn more about controlling which nodes your playbooks execute on, more sophisticated tasks, and the meaning of the output.

Beyond the basics

By default Ansible uses SFTP to transfer files. If the machine or device you want to manage does not support SFTP, you can switch to SCP mode in Configuring Ansible. The files are placed in a temporary directory and executed from there.

If you need privilege escalation (sudo and similar) to run a command, pass the become flags:

# as bruce

$ ansible all -m ping -u bruce

# as bruce, sudoing to root (sudo is default method)

$ ansible all -m ping -u bruce –become

# as bruce, sudoing to batman

$ ansible all -m ping -u bruce –become –become-user batman

You can read more about privilege escalation in Understanding privilege escalation: become.

Congratulations! You have contacted your nodes using Ansible. You used a basic inventory file and an ad hoc command to direct Ansible to connect to specific remote nodes, copy a module file there and execute it, and return output. You have a fully working infrastructure.

Resources

Buy us some coffee Thank You for your support as we work to give you the best of guides and articles.

top