Skip to main content

Command Palette

Search for a command to run...

Ansible

Published
7 min readView as Markdown
V

I am currently a B.Tech student pursuing Computer Science with a specialization in Data Science at I.T.S Engineering College. I am always excited to learn and explore new things to increase my knowledge. I have good knowledge of programming languages such as C, Python, Java, and web development.

Introduction to Ansible

In modern IT infrastructure, automation is crucial for managing configurations, deploying applications, and orchestrating tasks efficiently. Ansible, an open-source automation tool, simplifies these processes with an agentless architecture and human-readable YAML scripts. DevOps widely uses it for configuration management, application deployment, and IT orchestration.

Why Ansible?

Ansible is favored for several reasons:

  • Agentless: Unlike Puppet or Chef, Ansible doesn’t require agents on remote machines. It communicates using SSH.

  • Simple YAML Syntax: Playbooks are written in YAML, making them easy to understand and modify.

  • Idempotency: Ensures that executing the same task multiple times does not cause unwanted changes.

  • Scalability: Can manage thousands of servers with ease.

  • Extensive Integrations: Works with cloud providers, containers, and various automation tools.

Key Components of Ansible

  1. Inventory: A file defining the target servers (hosts) where tasks will be executed. Example:

     [webservers]
     server1 ansible_host=192.168.1.10  
     server2 ansible_host=192.168.1.11
    
  2. Modules: Predefined functions that perform specific tasks like installing software, copying files, or managing services. Example:

     - name: Install Nginx
       apt:
         name: nginx
         state: present
    
  3. Playbooks: YAML-based scripts containing tasks to automate workflows. Example:

     - name: Configure Web Server
       hosts: webservers
       tasks:
         - name: Install Apache
           apt:
             name: apache2
             state: present
    
  4. Roles: A structured way to organize playbooks, making them reusable and modular.

  5. Variables & Templates: Allow customization of configurations dynamically.

Ansible in Action: Sample Workflow

Step 1: Install Ansible

On a Linux-based control machine, install Ansible using:

sudo apt update && sudo apt install ansible -y  # Ubuntu/Debian

Step 2: Configure Inventory File

Define target hosts in /etc/ansible/hosts:

[webservers]
192.168.1.100 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_rsa

Step 3: Run Ad-hoc Commands

Ping all hosts to verify connectivity:

ansible all -m ping

Output:

192.168.1.100 | SUCCESS => {
    "ping": "pong"
}

Step 4: Create & Execute a Playbook

Create webserver.yml:

- name: Setup Web Server
  hosts: webservers
  become: yes
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present

Run the playbook:

ansible-playbook webserver.yml

Step 5: Verify Deployment

Check if Apache is running:

curl http://192.168.1.100

Use Cases of Ansible in DevOps

  • Configuration Management: Ensuring consistent configurations across multiple servers.

  • Application Deployment: Automating application releases without manual intervention.

  • Infrastructure Provisioning: Managing cloud resources in AWS, Azure, or GCP.

  • Security Automation: Enforcing compliance policies across systems.

Ansible Playbooks

An Ansible Playbook is a YAML-based script that defines a set of automation tasks to be executed on remote hosts. It is used for configuration management, application deployment, and infrastructure automation.

Basic Structure of a Playbook

A playbook consists of:

  • Hosts: Defines target machines.

  • Tasks: List of actions to be performed.

  • Modules: Built-in functions (e.g., apt, yum, service).

  • Handlers (Optional): Run tasks only when notified.

  • Variables (Optional): Store reusable values.

Example Playbook - Install Apache on Ubuntu

- name: Install and Configure Apache  
  hosts: webservers  
  become: true  

  tasks:  
    - name: Install Apache  
      apt:  
        name: apache2  
        state: present  

    - name: Start Apache Service  
      service:  
        name: apache2  
        state: started  
        enabled: true

How to Run the Playbook

ansible-playbook -i inventory.ini playbook.yml

Where inventory.ini contains the target server details.

Key Features:

  • Declarative & Readable: Uses YAML for easy understanding.

  • Idempotent: Ensures the same result on multiple executions.

  • Scalable: Can automate small tasks or complex workflows.

  • Reusable: Supports variables, loops, and roles for better structuring.

Ansible Playbooks make IT automation simple, efficient, and repeatable.

Task-01

  • Write an Ansible playbook to create a file on a different server

  • Write an Ansible playbook to create a new user.

  • Write an Ansible playbook to install Docker on a group of servers

Here are three Ansible playbooks for tasks:


Task 1: Create a File on a Remote Server

This playbook creates a file named sample.txt on a remote server.

Playbook: create_file.yml

- name: Create a file on a remote server
  hosts: all
  become: true

  tasks:
    - name: Create a file
      file:
        path: /home/ubuntu/sample.txt
        state: touch
        mode: '0644'

Run the playbook:

ansible-playbook -i inventory.ini create_file.yml

Task 2: Create a New User on a Remote Server

This playbook creates a user named devops_user with a home directory.

Playbook: create_user.yml

- name: Create a new user
  hosts: all
  become: true

  tasks:
    - name: Create a new user
      user:
        name: devops_user
        state: present
        createhome: yes
        shell: /bin/bash

Run the playbook:

ansible-playbook -i inventory.ini create_user.yml

Task 3: Install Docker on a Group of Servers

This playbook installs Docker on all servers under the [docker_hosts] group.

Playbook: install_docker.yml

- name: Install Docker on multiple servers
  hosts: docker_hosts
  become: true

  tasks:
    - name: Install required packages
      apt:
        name: ['apt-transport-https', 'ca-certificates', 'curl', 'software-properties-common']
        state: present

    - name: Add Docker GPG key
      apt_key:
        url: https://download.docker.com/linux/ubuntu/gpg
        state: present

    - name: Add Docker repository
      apt_repository:
        repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"
        state: present

    - name: Install Docker
      apt:
        name: docker-ce
        state: present

    - name: Start and enable Docker service
      service:
        name: docker
        state: started
        enabled: true

Run the playbook:

ansible-playbook -i inventory.ini install_docker.yml

These playbooks automate essential tasks using Ansible.

Ansible Project

Task-01

  • create 3 EC2 instances . make sure all three are created with the same key pair

  • Install Ansible in a host server

  • copy the private key from local to the Host server (Ansible_host) at (/home/ubuntu/.ssh)

  • access the inventory file using sudo vim /etc/ansible/hosts

  • Create a playbook to install Nginx

  • deploy a sample webpage using the Ansible playbook

Step 1: Create 3 EC2 Instances

We will use AWS CLI or Terraform to create 3 EC2 instances with the same key pair.

1.1 Create a Key Pair

Run this command in your terminal:

aws ec2 create-key-pair --key-name ansible-key --query 'KeyMaterial' --output text > ansible-key.pem
chmod 400 ansible-key.pem

2. Create EC2 Instances Using AWS CLI

aws ec2 run-instances --image-id ami-0abcdef1234567890 --count 3 --instance-type t2.micro \
    --key-name ansible-key --security-group-ids sg-xxxxxxxx \
    --subnet-id subnet-xxxxxxxx --tag-specifications \
    'ResourceType=instance,Tags=[{Key=Name,Value=Ansible-Host}]'
  • Replace ami-0abcdef1234567890 with the actual AMI ID (Amazon Machine Image).

  • Replace sg-xxxxxxxx and subnet-xxxxxxxx with your Security Group and Subnet ID.

  • This creates 3 EC2 instances with the same key pair.


Step 2: Install Ansible on Host Server

Once your EC2 instances are running, connect to one of them (which will be your Ansible control node) using SSH:

ssh -i ansible-key.pem ubuntu@<Public_IP_of_host_server>

Install Ansible on the host server:

sudo apt update -y
sudo apt install software-properties-common -y
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible -y
ansible --version  # To verify installation

Now, the host server is set up with Ansible.


Step 3: Copy the Private Key to the Host Server

On your local machine, copy the private key (ansible-key.pem) to the host server using SCP:

scp -i ansible-key.pem ansible-key.pem ubuntu@<Host-Server-Public-IP>:~/

Then, log into the host server and adjust the key’s permissions:

chmod 400 ansible-key.pem

Step 4: Configure the Inventory File

Once inside the host server, edit the Ansible inventory file:

sudo vim /etc/ansible/hosts

Add the following lines:

[webservers]
web1 ansible_host=<EC2-Instance-1-Public-IP> ansible_user=ubuntu ansible_ssh_private_key_file=~/ansible-key.pem
web2 ansible_host=192.168.1.102 ansible_user=ubuntu ansible_ssh_private_key_file=ansible-key.pem
web3 ansible_host=192.168.1.103 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/ansible-key.pem

Save and exit.

Verify Connectivity

Run the following command on the host server to verify if Ansible can connect to the EC2 instances:

ansible all -m ping

Expected Output:

server1 | SUCCESS => { "changed": false, "ping": "pong" }
server2 | SUCCESS => { "changed": false, "ping": "pong" }
server3 ansible_host | SUCCESS

If any connection fails, check the key permissions:

chmod 400 ~/.ssh/ansible-key.pem

Step 5: Install Nginx using Ansible Playbook

Create the playbook file:

Playbook: install_nginx.yml

- name: Install and Configure Nginx on EC2
  hosts: webservers
  become: true

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present
        update_cache: yes

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: yes

Run the playbook:

ansible-playbook -i /etc/ansible/hosts install_docker.yml

Verify Nginx is running:

curl http://<EC2-Public-IP>

Step 6: Deploy a Web Page using Ansible Playbook

Now, let’s create a playbook to deploy an index.html file to serve a basic webpage.

Playbook: deploy_website.yml

- name: Deploy a simple website
  hosts: webservers
  become: true

  tasks:
    - name: Install Nginx
      apt:
        name: nginx
        state: present

    - name: Copy HTML file to web server
      copy:
        content: "<h1>Welcome to my Ansible-managed website</h1>"
        dest: /var/www/html/index.html
        mode: '0644'

    - name: Restart Nginx
      service:
        name: nginx
        state: restarted

Run the playbook:

ansible-playbook -i inventory.ini install_docker.yml

Verify by visiting http://<EC2-PUBLIC-IP> in your browser.


More from this blog

Vanshika Sharma

38 posts

B.Tech Data Science, Expert in C, Python, Java, and Full-Stack Web Development. Knowledge in Problem Solving Languages.