Ansible Hands-On Lab For 😲Beginners:
Simplifying Infrastructure Automation

First, let us understand the need to learn this tool and why it is required.

Introduction
Ansible is a robust tool used in DevOps for automating tasks related to deploying, setting up, and managing computer systems. It uses simple language to describe how systems should be configured, making it straightforward to coordinate actions across various machines, networks, and platforms.
Why to learn
The primary goal of learning Ansible is to automate the configuration of files, packages, and operations across multiple servers using a simple YAML file. This eliminates the need for manual intervention and streamlines the process of managing and maintaining server configurations efficiently.
Some common features which need to know.
Simplified Infrastructure Management
Cross-Platform Compatibility
Infrastructure as Code (IaC)
Agentless Architecture
Architecture of Ansible
Agentless Design: Ansible operates without requiring agents on managed hosts, simplifying deployment and management.
Control Node: The control node is where Ansible software is installed and manages inventory and task execution.
Inventory: Ansible uses an inventory file to list and group-managed hosts, allowing for dynamic management of infrastructure.
Playbooks: Playbooks, written in YAML, define tasks and desired system states, enabling automation and flexibility in workflows.

Steps to do Hands-On
Step 1.
Deploy four VMs in AWS using EC2, including one controller-server(master) and three Host-servers:

To configure the deployment:
Select Ubuntu as the operating system.
Choose t2.micro as the instance type.
In the security group, enable access to HTTP and HTTPS ports, while leaving other settings as default.
Make a key(ansible.pem) for accessing the server through ssh and make sure to give the same key for all the host's servers.
Step 2.
Login into the ansible-master server through ssh.


# Open any linux based terminal (ps: use Git bash for window user)
# Make sure you are in the location where the .pem is downloaded.
# First change the permission of the file
chmod 400 ansible-master.pem
# Then use ssh command to login, for the first time it asking for confirmation
ssh -i "ansible-master.pem" ubuntu@ec2-<your-IP>.ap-south-1.compute.amazonaws.com
Step 3.
In the terminal first run the update command and then install Ansible

sudo apt update # Then
sudo apt-add-repository ppa:ansible/ansible # it will add the ansible repo
sudo apt update # Update again
sudo apt install ansible # for the installation
ansible --version # check the version

Step 4.
Setup the host server in the host's file
sudo vi /etc/ansible/hosts
# and press i key to write down the instruction

[servers] and [prd] are the groups in which we put the different server's IPs.
server_1 - In this way, we can write the name of the server
ansible_host - it is a variable for setting up the IPs of the host-server in this file.
after that save the file by pressing esc and then :wq to save
Step 5.
In the terminal create a new folder name as keys

Import the key from your local system to your ec2 server for that use this command from your local system terminal and make sure you were present at the key location.
scp -i <C:/Users/asus/Dropbox/PC\ \(2\)/Downloads/prod-test.pem> <C:/Users/asus/Dropbox/PC\ \(2\)/Downloads/prod-test.pem> <ubuntu@13.232.157.115:/home/ubuntu/keys>
# Make sure replace your input in the field of <>.
Note: Explanation of the command:
"scp": Stands for "secure copy" and is a command-line tool for securely transferring files between hosts.
"-i C:/Users/asus/Dropbox/PC\ 22/Downloads/prod-test.pem": Specifies the private key file used for authentication. In this case, the path to the private key file is provided.
"C:/Users/asus/Dropbox/PC\ 22/Downloads/prod-test.pem": Specifies the path of the file to be copied from the local machine.
"ubuntu@13.232.157.115": Specifies the username (ubuntu) and the IP address (13.232.157.115) of the remote server.
":/home/ubuntu": Specifies the destination path on the remote server where the file will be copied to. In this case, it is the "/home/ubuntu" directory.
Overall, this command uses SCP to copy the file "prod-test.pem" from the local machine to the remote server at IP address 13.232.157.115, with the specified destination path of "/home/ubuntu" on the remote server. The private key is used for authentication to establish a secure connection during the file transfer.

Step 6.
Now go to the host's file again and write down the functionality for how to access the host's servers
sudo vi /etc/ansible/hosts

[all:vars]: This line signifies that the following variables apply to all hosts defined in the inventory file. But we can also specific group names as I mentioned above image.
ansible_python_interpreter=/usr/bin/python3: This variable specifies the path to the Python 3 interpreter that Ansible should use when executing tasks on the managed hosts. It ensures compatibility and proper execution of Ansible modules and scripts.
ansible_user=ubuntu: This variable sets the username (ubuntu) that Ansible will use when connecting to the managed hosts. It determines the user account through which Ansible will execute commands and perform configurations.
ansible_ssh_private_key_file=/home/ubuntu/keys/ansible-master.pem: This variable points to the location of the private key file (ansible-master.pem) on the control node. Ansible uses this key file for SSH authentication when connecting to the managed hosts. It ensures secure and authenticated communication between the control node and the remote hosts.
After that save the file.
Step 7.
Now check if our master server can ping to the host server or Not.
By using this command -
ansible <server-grp-name> -m ping
# check more command like this
ansible <server-grp-name> -a "free -h"
ansible <server-grp-name> -a "sudo apt update"

Here we are successfully connected to the host's servers.
There a concept comes,
ansible adhoc commands are one-line commands used for quick tasks, while modules are reusable scripts that provide more functionality and flexibility for complex automation tasks in Ansible.
Ansible modules are units of code that can control system resources or execute system commands
we can also check the operation and permission that our inventory(host file) will perform
ansible-inventory --list

Step 8.
Now we learn how to write the playbook script for automated configuration throughout all the servers.
Here is what we do, we will deploy a static website with the help of an Nginx web server in one of our host servers.
# In master terminal first create a folder named playbooks
cd /home/ubuntu
mkdir playbooks
cd playbooks
sudo vim deploy_static_play.yml
Now in Vim editor, we will write the Yaml to automate all the tasks
-
name: Install nginx and serve static website
hosts: prd
become: yes
tasks:
- name: Install nginx
apt:
name: nginx
state: latest
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
- name: Deploy web page
copy:
src: index.html
dest: /var/www/html
This YAML file represents an Ansible playbook that performs the following tasks:
The playbook has a name "Install nginx and serve static website" and targets the hosts specified under the "prd" group.
The playbook requires elevated privileges and uses the "become" keyword to execute tasks as a privileged user (e.g., using sudo).
The playbook consists of multiple tasks defined under the "tasks" section.
The first task is named "Install nginx" and uses the "apt" module to ensure the latest version of nginx is installed.
The second task is named "Start nginx" and uses the "service" module to ensure the nginx service is running and enabled to start on boot.
The third task is named "Deploy web page" and uses the "copy" module to copy the "index.html" file from the current directory (or specified source) to the destination "/var/www/html" on the target hosts.
Overall, this playbook installs nginx, starts the nginx service, and deploys a static web page to the specified location on the target hosts.

Step 9.
Now we have to create the index.html in our playbooks folder so for that we have to write the code for it. But for you guys, you can pick the code from here.
Sudo vim index.html
<!DOCTYPE html>
<html>
<head>
<title>Cool Web Page</title>
<style>
/* Add your custom CSS styles here */
body {
font-family: Arial, sans-serif;
background-color: #f1f1f1;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
text-align: center;
margin-top: 50px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
p {
color: #666;
line-height: 1.5;
}
.cta-button {
display: inline-block;
padding: 10px 20px;
background-color: #333;
color: #fff;
text-decoration: none;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to My Cool Web Page</h1>
<p>This is a simple example of a static web page created using HTML.</p>
<p>You can customize and enhance it to build your own awesome web page!</p>
<p>Feel free to add more sections, images, links, and interactive elements to make it unique.</p>
<p>Get started by editing this HTML file with your favorite text editor.</p>
<p>Enjoy coding and have fun!</p>
<p>
<a class="cta-button" href="https://hitanshu-portfolio.netlify.com">For Portfolio</a>
</p>
</div>
</body>
</html>
Then save this file
Now Run the ansible-playbook script by using this command
ansible-playbook deploy_static_play.yml
Output:

Step 10.
Now this is our final step to check the execution which we did with the help of ansible-playbook
you have to select the public IP of that host-server and then paste it on any browser search engine

Final Output:

Points to be noted
when we make EC2 on AWS, at the time of allocation the public IP is different, and when you stop that sever and start again after some time then the IP will change because it is dynamically allocated.
To resolve this issue do two things, 1) Set up the elastic IP which cost you and 2) Change the IP in the inventory(hosts) file in the master server every time (which cost nothing if you are under a free-tier subscription).
