π Ansible: The Magic Wand of IT Automation β¨


ππWhat we learn in this Blogππ
What is Ansible ??π€β¨
Configuration Managementπ€
Push Based vs Pull Basedπ
How to install Ansible
Host Inventory
YAML
Playbooks
Hands on
Conclusion.
Unlocking the Power of Ansible: A Brief Guide π
Hey there, tech adventurers! π
Ready to level up your IT game? Say hello to Ansible, the magical tool that makes managing your servers as easy as waving a wand. πͺ Whether youβre a sysadmin, developer, or just a curious soul, Ansible is here to sprinkle some automation fairy dust over your infrastructure. Letβs dive into why Ansible is your new best friend! π€
π What is Ansible?
Ansible is an open-source automation tool that simplifies IT orchestration, configuration management, and application deployment. It uses a simple, human-readable language (YAML) to define tasks, making automation accessible to everyone. π
Ansible is one among the DevOps Configuration management tools which is famous for its simplicity. It is an open source software developed by Michael DeHaan and its ownership is on RedHat.
Ansible is an open source IT configuration Management, Deployement & Orchestration tool.
This tool is very simple to use yet powerful enough to automate complex multi-tier IT application environments.
The main component of ansible are playbooks. configuration management and deployment.
just you want to specify what state you want the system to be in and ansible take care of it.
Ansible was written in python.
π Key Features of Ansible
Agentless: No need to install agents on managed nodes, reducing complexity and overhead. π₯οΈπ
Versatile: Works seamlessly across diverse platforms including Linux, Windows, and cloud environments. π
Scalable: From managing a few servers to thousands, Ansible scales effortlessly. π
Community-driven: Continuously evolving with contributions from a vibrant community of users and developers. π€
Configuration Management π
Configuration Management: Automate server setups, software installations, and system configurations.
It is a method through which we automate admin task.
Configuration Management tool turns your code into Infrastructure.
so your code would be testable, repeatable and Versionable.
Infrastructure refers to the composite of -
software
Network
People
Process
Push Based vs Pull Based
Tools like Puppet and chef are pull based
Agent on the server periodically checks for the configuration information from central server (master)
Ansible is Push Based
Central server pushes the configuration information on target servers. You control when the changes are made on the servers
(Ansible send notification to host servers to perform task )
What Ansible can do ??
Configuration Management
App Deployment
Continous Delivery
π§ββοΈ How Does Ansible Work?
Ansible works by connecting to your nodes and pushing out a small program called Ansible Module to them .
Then Ansible executed these modules and removed them after finished. The library of module can reside on any machine. and there are no daemons ,servers, or databases required.
The Management node is the controlling node that controls the entire execution of the playbook.
The inventory file provide the list of hosts where the Ansible modules to be run.
The management node makes an SSH connection and executes the small modules on the host's machine and install the software.
Ansible removes the modules once those are installed so expertly.
It connect to the host machine executes the instructions, and if it is successfully installed, then remove that code in which one was copied on the host machine.
Ansible basically consists of three components
Managed Nodesπ οΈ
Managed Nodes are stored in the hosts file for Ansible Automation.
Ansible Playbooksπ
Ansible playbooks are expressed in YAML format and server as the repository for the various tasks that will be executed on the Managed Nodes (host)
Playbooks are a collection of tasks that will be run on one or more hosts.
Inventory Fileπ§
Ansible's inventory hosts file is used to list and group your servers. its default location is /etc/ansible/hosts
Note: In inventory host file we can mention IP address or Hostname also
Sample of Inventory file
[webservers]
web1.example.com
#web2.example.com
[databases]
192.168.1.20
192.168.1.21
db1.example.com
db2.example.com
Important Points about Ansible Inventory File
Default Location: The default location for the inventory file is
/etc/ansible/hosts
.Format: The inventory file can be in INI or YAML format. The INI format is more common and straightforward.
Grouping: Hosts can be grouped into categories, such as
[webservers]
or[databases]
, to apply tasks to multiple hosts simultaneously.Hostnames and IP Addresses: You can list hosts by their hostnames or IP addresses.
Variables: You can define variables for groups or individual hosts within the inventory file. These variables can be used in playbooks to customize tasks.
Dynamic Inventory: Ansible supports dynamic inventory scripts, which can pull inventory data from external sources like cloud providers.
Nested Groups: Groups can be nested within other groups, allowing for more complex and hierarchical organization of hosts.
Aliases: Hosts can have aliases for easier reference in playbooks.
Comments: Lines starting with
#
are treated as comments and are ignored by Ansible.
π¦Ansible setup π¦
Create Ubuntu system in AWS (free tier eligible) EC2 machine
Ansible system
Host system (it could 100 machine according to your requirement)
This is optional step you can also skip but its is best practice to create ansible user
Connect to the all the machine using Git-bash and create ansible user by following command .
sudo useradd ansible
sudo passwd ansible
Now confirm the password
Open the visudo and configure below detail
ansible All=(All) NOPASSWD:ALL
Now open vi/etc/ssh/sshd_config file and comment the PasswordAuthentication no
and un-comment the PasswordAuthentication yes
sudo vi /etc/ssh/sshd_config
#PasswordAuthentication no
PasswordAuthentication yes
Restart the server
sudo service sshd restart
Note : Do all above steps on every machine , this steps optional but it is highly recommended its is a best practice.
Install Ansible in control node
from here you don't miss any step
Switch to Ansible User
sudo su ansible
Install packages
sudo apt-add-repository ppa:ansible/ansible
update the packages
sudo apt update -y
Install ansible
sudo apt install ansible -y
Now check version
ansible --version
create folder
mkdir keys
Now copy the .pem file from your local to remote Machine by using scp command (run this command on your local )
scp -i "divya.pem" divya.pem ubuntu@ec2-13-127-5-106.ap-south-1.compute.amazonaws.com:/home/ubuntu/keys
verify that your .pem file (key_file) is present on keys folder which we cerate
Now go to your hosts file (Inventory file) and make some configuration like Host_IP
and pass variable (all:vars) where you can specify you key file location
Reverify that you configure all detail correctly
sudo vim /etc/ansible/hosts
Give permission to your key
chmod 600 /home/ubuntu/keys/divya.pem
check your connectivity (that your master node attach to host node or not)
ansible all -m ping
Heyyyyyy hurayyyyy with this Ansible setup is completed
Ansible Ad Hoc Commands
Ansible ad hoc commands are a powerful feature that allows you to run simple commands or tasks directly on managed nodes without needing to write a full playbook. This can be useful for quick checks, debugging, or performing one-off tasks.
Basic Syntax for Ansible Ad Hoc Commands
The general syntax for running an ad hoc command is:
ansible [Hostgroup,ip,hostname] -m [module] -a "[command]"
Where:
[group,ip,Hostname]
is the host or group of hosts on which you want to run the command.-m [module]
specifies the Ansible module to use (e.g.,command
,shell
,ping
).-a "[command]"
specifies the arguments for the module.
Common Examples of Ansible Ad Hoc Commands
ansible all -m ping = Use the
ping
module to check connectivity to the hostsansible all -m shell -a "df -h" =Use the
shell
module to execute a command. For example, to check the disk usage on all hostsansible all -m shell -a "uptime" =To check the uptime of all hosts
ansible all -m copy -a "src=/path/to/file.txt dest=/tmp/file.txt" =Use the
copy
module to copy a file from the control node to the managed nodes. For example, to copyfile.txt
to/tmp
on all nodesansible all -m apt -a "name=vim state=present =Use the
apt
module (for Debian-based systems) to install a packageansible all -m service -a "name=nginx state=restarted"=Use the
service
module to start, stop, or restart services. For example, to restart thenginx
service on all hostsansible all -m apt -a "name=vim state=absent" --become =Use the
yum
ordnf
module to remove software packages. For example, to uninstallvim
ansible all -m command -a "systemctl status nginx" =Check Status of a Service
ansible all -m command -a "ip a" =Get Network Interfaces
ansible all -m file -a "path=/tmp/newdir state=directory" --become =Create a Directory
Irrespective of underlying OS which we can use to manage packages(software) using package manager in Ansible ????
Ans : Ansible introduced "package manager" to work with underlying package manager.
π YAML: The Friendly Data Serialization Format π
π― What is YAML?
YAML stands for "YAML Ain't Markup Language" (a recursive acronym) or "Yet Another Markup Language." It's a human-readable data serialization standard that's often used for configuration files and data exchange. Think of YAML as the cool, more readable cousin of JSON and XML. πβ¨
π οΈ Practical Uses of YAML
Here are some common scenarios where YAML shines:
Configuration Files: Applications like Docker and Kubernetes use YAML to define configurations and deployment setups. π’π οΈ
Data Serialization: YAML is great for storing and exchanging data between applications or systems. ποΈ
Documentation: Many documentation tools use YAML to define metadata and configurations. π
Ansible Playbooks
π What is an Ansible Playbook?
An Ansible playbook is a YAML file that defines a set of tasks to be executed on remote systems. Itβs a way to automate tasks like software installation, configuration changes, and system management. Think of it as a recipe for your infrastructure! ππ½οΈ
π Key Components of a Playbook
Play: A play defines a set of tasks to be executed on a group of hosts. Itβs like a chapter in your book of automation. π
Tasks: Tasks are the individual actions within a play. Each task uses an Ansible module to perform an action. π οΈ
Modules: Modules are the building blocks of tasks. They are predefined functions that Ansible uses to perform actions like installing packages, copying files, and more. π§
Variables: Variables store data that can be reused in playbooks. They make your playbooks flexible and dynamic. π’
Handlers: Handlers are special tasks that only run when notified by other tasks. They are great for managing services and performing actions only when changes occur. π
π οΈ Writing Your First Ansible Playbook
Letβs get started with a simple example. Weβll create a playbook that installs Nginx webserver on a remote server and ensures the service is running.
Step 1: Define the Playbook
Create a file named setup-nginx.yml
and add the following content:
---
- name: Setup NGINX Server
hosts: webservers
become: yes
tasks:
- name: Install NGINX
apt:
name: nginx
state: present
update_cache: yes
- name: Start and enable NGINX service
service:
name: nginx
state: started
enabled: yes
- name: Deploy custom HTML page
copy:
src: index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
Step 2: Create the HTML File
Create a file named index.html
in the same directory as your playbook with the content you want to serve. For example: (you can change html code according to your requirement)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learn with Divya - Magical & Fun</title>
<style>
body {
margin: 0;
padding: 0;
font-family: 'Arial', sans-serif;
color: #ffffff;
background: linear-gradient(135deg, #ff7f50, #40e0d0, #d1a4a4);
background-size: 300% 300%;
animation: gradientAnimation 15s ease infinite;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
text-align: center;
}
@keyframes gradientAnimation {
0% { background-position: 0% 0%; }
50% { background-position: 100% 100%; }
100% { background-position: 0% 0%; }
}
.container {
background: rgba(0, 0, 0, 0.7);
padding: 40px;
border-radius: 20px;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.5);
max-width: 90%;
width: 600px;
margin: 20px;
position: relative;
overflow: hidden;
}
.container::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: url('https://www.transparenttextures.com/patterns/white-sand.png');
opacity: 0.2;
z-index: 1;
}
.container h1 {
margin-bottom: 20px;
font-size: 2.8em;
color: #ff1493;
z-index: 2;
position: relative;
}
.container p {
margin-bottom: 20px;
font-size: 1.2em;
line-height: 1.6;
color: #e0e0e0;
z-index: 2;
position: relative;
}
.container ul {
list-style: none;
padding: 0;
margin: 0;
font-size: 1.1em;
color: #ffeb3b;
z-index: 2;
position: relative;
}
.container ul li {
margin: 10px 0;
}
.button {
display: inline-block;
padding: 15px 25px;
margin: 10px;
font-size: 1.2em;
color: #ffffff;
background: #1e90ff;
text-decoration: none;
border-radius: 10px;
transition: background 0.3s ease, transform 0.3s ease;
z-index: 2;
position: relative;
}
.button:hover {
background: #ff6347;
transform: scale(1.05);
}
.footer {
margin-top: 30px;
font-size: 0.9em;
color: #cccccc;
z-index: 2;
position: relative;
}
@media (max-width: 768px) {
.container {
width: 90%;
padding: 20px;
}
.container h1 {
font-size: 2em;
}
.container p, .container ul li {
font-size: 1em;
}
.button {
padding: 12px 20px;
font-size: 1em;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to Learn with Divya! β¨</h1>
<p>
Dive into a world where knowledge meets magic. <strong>Learn with Divya</strong> brings you engaging content and enchanting tutorials.
</p>
<p>
Discover:
<ul>
<li>π Exciting Tutorials</li>
<li>π§© Interactive Tips</li>
<li>π Trendy Insights</li>
<li>π Fun Challenges</li>
</ul>
</p>
<a href="https://learnwithdivya.hashnode.dev/" class="button">Explore the Blog</a>
<div class="footer">
© 2024 Learn with Divya. All
Explanation of the Playbook π
name: Setup NGINX Server
: Describes the playbook.hosts: webservers
: Specifies the group of hosts where the tasks will be executed. You should have this group defined in your inventory file.become: yes
: Indicates that the tasks require elevated privileges (sudo).
Tasks:
- name: Install NGINX
apt:
name: nginx
state: present
update_cache: yes
name: nginx
: The package name for NGINX.state: present
: Ensures the NGINX package is installed.update_cache: yes
: Updates the package cache before installing.2) Start and Enable NGINX Service:
- name: Start and enable NGINX service service: name: nginx state: started enabled: yes
state: started
: Ensures the NGINX service is running.enabled: yes
: Configures the service to start on boot.
3) Deploy Custom HTML Page:
- name: Deploy custom HTML page
copy:
src: index.html
dest: /var/www/html/index.html
owner: www-data
group: www-data
mode: '0644'
src: index.html
: The source HTML file to copy.dest: /var/www/html/index.html
: The destination path on the remote server.owner: www-data
: Sets the file owner.group: www-data
: Sets the file group.mode: '0644'
: Sets the file permissions.
Step 3: Run the Playbook
Execute the playbook using the ansible-playbook
command:
ansible-playbook setup-nginx.yml
before you access the application open all traffic rule in your Inbound rule
Access your application Now : URL : http : // EC2-VM-Public-IP
Test Results :
Connecting host node success
Ansible playbook works : Task completed
Access your application paste host node IP address on browser : website Deploy
Conclusion π
With this playbook, youβve automated the installation and configuration of NGINX and deployed a custom HTML page. Playbooks like this one save time and ensure consistency across your servers. π
This command will apply the tasks defined in your playbook to the hosts specified. Youβll see output showing the progress of each task. π οΈπ
Thatβs a wrap on our magical journey through Ansible! πβ¨ From the basics to advanced features, Ansible is a powerful tool that can transform your IT operations. Dive in, explore, and let automation make your life easier and more fun! ππ
Feel free to leave your thoughts, questions, or Ansible tips in the comments below. Happy automating! π€πͺ
Subscribe to my newsletter
Read articles from Divya vasant satpute directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Divya vasant satpute
Divya vasant satpute
, I'm a seasoned DevOps engineer π οΈ with a knack for optimizing software development lifecycles and infrastructure operations. π‘ Specializing in cutting-edge DevOps practices and proficient in tools like Docker, Kubernetes, Ansible, and more, I'm committed to driving digital transformation and empowering teams to deliver high-quality software with speed and confidence. π»