Automate Everything with Ansible

Dea Agra Larasati
8 min readMay 6, 2023

--

In today’s fast-paced digital world, automation is a crucial part of any organization’s strategy. With the rise of cloud computing, DevOps, and continuous integration and delivery, the demand for automation tools has grown exponentially. Ansible, an open-source automation tool, has emerged as one of the most popular solutions for automating infrastructure management, application deployment, and configuration management.

In this post, we will look at how Ansible can help you automate everything in your infrastructure.

What is Ansible?

Ansible is an open-source automation tool that provides a simple and powerful way to automate IT tasks. Ansible was developed by Red Hat and is now part of IBM. It allows users to automate tasks such as configuration management, application deployment, and orchestration across multiple servers and devices, making it an essential tool for DevOps teams.

Ansible uses a declarative language called YAML to define tasks, which makes it easy to read and understand. It is agentless, which means that it doesn’t require any software to be installed on the target servers or devices. Instead, it uses SSH (Secure Shell) or WinRM (Windows Remote Management) to connect to the target devices and execute the tasks.

Ansible enables users to automate practically any process, from simple activities such as generating user accounts to large multi-tier application deployments. Ansible provides a user-friendly interface for developing, maintaining, and executing automation processes thanks to its straightforward and easy-to-understand syntax. This makes it a perfect tool for IT professionals, DevOps teams, and system administrators that want to optimize their workflows and save time and effort managing their infrastructure.

Ansible Architecture

Ansible Architecture

From the picture we can see that Ansible architecture involves a control node, playbook, inventory, SSH to connect to managed/targeted nodes.

The control node is where Ansible is installed, and from where automation tasks are executed. Managed/targeted nodes are the servers that Ansible manages and configures.

To begin using Ansible, it is necessary to first install Ansible on the control node. Once you have installed Ansible, you will need to register your targeted/managed hosts in the Ansible inventory. The inventory is a file that contains a list of all the hosts you want Ansible to manage, along with their IP addresses or hostnames.After that, you can create playbooks, which are YAML files containing a series of tasks to be executed on the managed nodes. These tasks can include a wide range of operations, such as installing software, configuring services, and managing network settings.

When the playbook is run from the control node, Ansible establishes a secure communication channel with the managed nodes using SSH. Ansible then executes the tasks defined in the playbook on the managed nodes.

Ansible Playbook Components

  • Name: The name is used to identify the playbook.
  • Hosts: Hosts are specified in the inventory file, which is a file that contains a list of the hosts and their attributes. The inventory file is typically located at /etc/ansible/hosts, but can be located anywhere on the control node and can be named anything.
  • Become: The become section specifies the user or privilege escalation method used to execute tasks with elevated privileges.
  • Variables: Variables are used to define values that can be reused throughout the playbook. Here are some examples of defining variables:
---
- name: Example playbook
hosts: all
vars:
my_var: "Hello, World!"
tasks:
- name: Print message
debug:
msg: "{{ my_var }}"
  • Tasks: A unit of work that is executed on a target host. Tasks are defined in a playbook and can include a variety of actions, such as installing packages, modifying configuration files, or starting and stopping services
  • Handlers: Handlers are tasks that are executed only when specific conditions are met, such as after a change has been made. They are often used to restart services or reload configuration files after changes have been made. Handlers are defined in the playbook and are triggered by a “notify” directive in a task. Handlers are defined in the same way as tasks, but with a different name. Here’s an example:
tasks:
- name: Update web server configuration
template:
src: web.conf.j2
dest: /etc/httpd/conf.d/web.conf
notify: Restart web server

handlers:
- name: Restart web server
service:
name: httpd
state: restarted
In this example, the "template" task updates the web server configuration file and notifies the "Restart web server" handler. The handler task uses the "service" module to restart the web server. If the configuration file was not changed, the handler task will not be executed.
  • Roles: Roles are collections of tasks and variables that can be reused across multiple playbooks.
  • Templates: Templates are files that can be customized for each host during the playbook execution.
  • Files: Files are copied from the control node to the target hosts during the playbook execution.
  • Conditional statements: Conditional statements allow the playbook to execute tasks only if certain conditions are met.

How to Install Ansible

Ansible can be installed on any operating system, but for this tutorial, I will demonstrate how to install Ansible on CentOS 7

  • Make sure your CentOS 7 system is up to date by running the command:
sudo yum update
  • Next, add the EPEL (Extra Packages for Enterprise Linux) repository by running the command:
sudo yum install epel-release
  • Then, install Ansible by running the command:
sudo yum install ansible
  • After Ansible is installed, verify that the installation was successful by running the command:
ansible --version
  • Configure Ansbile hosts

Edit the hosts configuration with this command vi /etc/ansible/hosts, then add the IP managed servers in this configuration file:

# This is the default ansible 'hosts' file.
#
# It should live in /etc/ansible/hosts
#
# - Comments begin with the '#' character
# - Blank lines are ignored
# - Groups of hosts are delimited by [header] elements
# - You can enter hostnames or ip addresses
# - A hostname/ip can be a member of multiple groups

# Ex 1: Ungrouped hosts, specify before any group headers.

## green.example.com
## blue.example.com
## 192.168.100.1
## 192.168.100.10

# Ex 2: A collection of hosts belonging to the 'webservers' group

## [webservers]
## alpha.example.org
## beta.example.org
## 192.168.1.100
## 192.168.1.110

# If you have multiple hosts following a pattern you can specify
# them like this:

## www[001:006].example.com

# Ex 3: A collection of database servers in the 'dbservers' group

## [dbservers]
##
## db01.intranet.mydomain.net
## db02.intranet.mydomain.net
## 10.25.1.56
## 10.25.1.57

# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com

[servers]
192.1.10.123
192.1.10.124
  • Configure SSH key-based authentication
ssh-keygen

This will create a public key file (~/.ssh/id_rsa.pub) and a private key file (~/.ssh/id_rsa) in your home directory.

  • Copy the public key to the managed nodes.
ssh-copy-id root@192.1.10.123
ssh-copy-id root@192.1.10.124

root is username on the managed node, and 192.1.10.123 and 191.1.10.124 is IP address of the managed node.

  • Test the SSH connection
ssh root@192.1.10.123
ssh root@192.1.10.124

This should log you in to the managed node without prompting you for a password.

  • Test if Ansible is able to connect to managed hosts
ansible -m ping all

If everything is set up correctly, you should see output like the following:

Ansible Use Case

For the purpose of demonstrating an example use case, I will show you how to automate the process of opening firewall ports 9200 and 5601 for multiple servers. In this scenario, the servers in question have IP addresses of 192.1.10.123 and 192.1.10.124.

  • Go to /etc/ansible/ and create playbook with this command vi open-port-playbook.yml and write the playbook with the following content:
- name: Configure Firewall
hosts: servers
become: true
tasks:
- name: Allow Elasticsearch port 9200/tcp
firewalld:
port: 9200/tcp
permanent: yes
state: enabled
zone: public
- name: Allow Kibana port 5601/tcp
firewalld:
port: 5601/tcp
permanent: yes
state: enabled
zone: public
  • - name: Configure Firewall line defines the name of the Ansible playbook.
  • hosts: serverline specifies the name of the Ansible inventory group that contains the server(s) on which the playbook will be executed which is 192.1.10.123 & 192.1.10.124 that we have configured in /etc/ansible/hosts.
  • become: true line specifies that Ansible should escalate privileges to become the root user on the target server(s) in order to modify firewall settings.
  • tasks: section defines the tasks that the playbook will perform.
  • - name: Allow Elasticsearch port 9200/tcp line defines the name of the first task, which is to allow access to port 9200/tcp.
  • firewalld: line specifies the Ansible module that will be used to modify the firewall settings.
  • port: 9200/tcp line specifies the port and protocol to be opened.
  • permanent: yes line indicates that the firewall rule will persist across reboots.
  • state: enabled line specifies that the firewall rule should be enabled.
  • zone: public line specifies the firewall zone in which the rule will be added.
  • name: Allow Kibana port 5601/tcp line defines the name of the second task, which is to allow access to port 5601/tcp.
  • firewalld: line specifies the Ansible module that will be used to modify the firewall settings
  • port: 5601/tcp line specifies the port and protocol to be opened for Kibana.
  • permanent: yes line indicates that the firewall rule for Kibana will persist across reboots. If you want to open the ports temporarily, set permanent to no.
  • state: enabled line specifies that the firewall rule for Kibana should be enabled.
  • zone: public line specifies the firewall zone in which the rule for Kibana will be added.

Save the file and in the same directory run the following command:

ansible-playbook -i hosts open-port-playbook.yml

Where:

  • ansible-playbook is the Ansible command to run a playbook.
  • -i hosts specifies the inventory file containing the target server(s) that this playbook will run on which is 192.1.10.123 & 192.1.10.124
  • open-port-playbook.yml is the name of the playbook file to run.

Conclusion

In conclusion, Ansible is a powerful open-source automation tool that allows you to manage and configure multiple servers from a single control machine. It uses a simple YAML-based syntax for defining playbooks that automate a wide range of tasks, including installing software, configuring services, and managing network settings. With Ansible, you can reduce manual errors, increase efficiency, and standardize your infrastructure configuration across your entire organization. Whether you’re managing a small or large IT environment, Ansible can help you streamline your processes and improve productivity. So, if you’re looking for a reliable automation tool that can simplify your daily operations, Ansible is definitely worth considering.

--

--