Photo by Taylor Vick on Unsplash

Introduction to Ansible — a speed run

Tanay Sojwal
WhatfixEngineeringBlog
6 min readJan 6, 2023

--

Introduction

Ansible is an open-source IT automation engine that automates provisioning, configuration management, application deployment, orchestration, and many other IT processes.

In simple words, Ansible can automate completing complex manual tasks that you need to do on your infrastructure that would rather cost you time and effort with almost zero errors. From automating your redundant day-to-day tasks to deploying complex applications on multiple remote servers, Ansible is one of the best choices in the IT automation business.

Concepts

At its core, Ansible works by connecting to your remote servers and pushing out small programs called modules to these servers. Modules are then used to accomplish their respective tasks on the servers.

Ansible uses an inventory file to keep track of the hosts that you want to manage and control in order to easily reference them inside ansible playbooks.

Playbooks are simply the junction at which the defined tasks are executed on referenced ansible inventory along with optional properties.

The management node in the picture depicted above is the control node where ansible is installed. This node controls the entire lifecycle of an ansible playbook on your remote nodes. The inventory file supplies the list of hosts where the modules orchestrated by the playbook need to be run. Ansible connects to the targeted remote nodes through SSH by default.

To limit the scope of this article, all examples will be performed on a local machine and not a remote server for the sake of simplicity. Note that the same playbook can be utilized for the same task on a remote server which requires only inventory configuration changes.

Inventory File

The default location of the ansible inventory file is “/etc/ansible/hosts”. The inventory contains server names, group definitions, connection configurations, etc. This file can be in INI or YAML formats. Below is an example of a typical inventory file.

mail.example.com

[webservers]
foo.example.com
bar.example.com

[dbservers]
one.example.com
two.example.com
three.example.com

The heading in brackets indicates the group names, which are used to classify hosts and resolve what hosts are to be targeted and for what purpose.

Run commands on local

Assuming you have ansible already installed, now we’ll try to run a simple command on our local to find out the disk usage of the system.

ansible localhost -c local -a "df -h"

For a remote server, the above command would look something like this.

ansible remote_server -a "df -h"

The output will look similar to this, where you can see disk usage by filesystems.

localhost | CHANGED | rc=0 >>
Filesystem Size Used Avail Use% Mounted on
udev 16G 0 16G 0% /dev
tmpfs 3.2G 2.9M 3.2G 1% /run
/dev/nvme0n1p2 468G 108G 337G 25% /
tmpfs 16G 186M 16G 2% /dev/shm
tmpfs 5.0M 4.0K 5.0M 1% /run/lock
tmpfs 16G 0 16G 0% /sys/fs/cgroup

Now we have learned how to run ansible commands manually. In an ideal case, you won’t want to do that. What you need is a playbook with all appropriate tasks listed which can be run or re-run to achieve the desired state of the target system.

Let’s create a simple playbook that clones an ansible examples repository. Let us create a directory for our ansible files with the below command.

mkdir ansible_tut

Now create main.yml inside our new directory with the following content.

---
- hosts: localhost
connection: local

tasks:
- name: Change dir and run git clone
command: git clone https://github.com/ansible/ansible-examples.git
args:
chdir: /home/tanaysojwal/Desktop/work/lab/ansible_tut/
register: git_result

- debug:
var: git_result

In the above playbook, we defined the host we want to run the playbook on, the type of connection, and the list of tasks. The only two things that are different are the register and the debug module which help us know the output of the git clone command. Now let’s run the playbook.

ansible-playbook main.yml

The output will look something like the one below.

PLAY [localhost] *************************************************************************************************

TASK [Gathering Facts] *******************************************************************************************
ok: [localhost]

TASK [Change dir and run git clone] ******************************************************************************
changed: [localhost]

TASK [debug] *****************************************************************************************************
ok: [localhost] => {
"git_result": {
"changed": true,
"cmd": [
"git",
"clone",
"https://github.com/ansible/ansible-examples.git"
],
"delta": "0:00:09.347584",
"end": "2022-12-19 14:03:48.249884",
"failed": false,
"msg": "",
"rc": 0,
"start": "2022-12-19 14:03:38.902300",
"stderr": "Cloning into 'ansible-examples'...",
"stderr_lines": [
"Cloning into 'ansible-examples'..."
],
"stdout": "",
"stdout_lines": []
}
}

PLAY RECAP *******************************************************************************************************
localhost : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

Module

Ansible works by connecting to your remote servers and pushing out small programs called modules to these servers. Modules are then used to accomplish their respective tasks on the servers. These programs are written in a way to achieve the desired state of the system. In case the desired state has already been achieved, no changes will be made to the system. This is known as the “idempotent” nature of Ansible which allows you to re-run commands without worrying about errors arising from bare script re-runs that we might have used otherwise. The beauty of ansible is that it removes the modules once those are installed so effectively it connects to the host machine, executes the tasks, and when successful removes the code which was copied on the remote machine in the first place.

Here’s an article with a list of must-know ansible modules if you’re going to be a regular at using ansible for your automation needs. https://opensource.com/article/19/9/must-know-ansible-modules

Roles

Roles are simply bundled tasks that are typically based on logical responsibilities. Let’s say you have a component A for which you are tasked to write an ansible playbook, you would want to create a “componentA” role. The main benefit of doing this is code reusability. “componentA” role can be reused by another playbook that might require it. It also makes your ansible code base look clean.

Let’s create a “gitclone” role since our task is cloning a repo. Use the command below to quickly create a role.

ansible-galaxy init gitclone

Ansible galaxy is an online repository where people publish their roles for reusability.

The file system of a typical role is shown below

tanaysojwal@RRR-LAP-000:~/Desktop/work/lab/ansible_tut/roles/gitclone$ tree
.
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml

Now let’s try to package our git clone code inside our newly created role. Move the content from main.yml of our project root to main.yml under tasks of our newly created “gitclone” role as shown below.

---
# tasks file for gitclone
- name: Change dir and run git clone
command: git clone https://github.com/ansible/ansible-examples.git
args:
chdir: /home/tanaysojwal/Desktop/work/lab/ansible_tut/
register: git_result

- debug:
var: git_result

Your main.yml file in the project root should look like this.

---
- hosts: localhost
connection: local
roles:
- gitclone

Note that your role should be inside a roles folder in the project root. Now if you try to run the playbook you will see that the execution is done in the same order as it was done from the main.yml playbook before.

Summary

With these examples, you have learned the basic concepts of Ansible like inventories, modules, playbooks & roles, and how you can leverage them to automate your day-to-day redundant tasks or use them to manage your servers. Make sure that you check out other ansible modules available for you to leverage in your playbooks to automate almost anything in your interest.

Please feel free to send your queries if you have any. Cheers!

References and further reading

--

--