Skip to main content

Command Palette

Search for a command to run...

Ansible: A Comprehensive Guide to Automation

Updated
10 min read
T

Learning DevOps Engineer passionate about cloud computing, containerization, and automation. Currently exploring Docker, AWS, and CI/CD pipelines to build scalable and efficient workflows. Documenting my learning journey in blog. stay tuned with me for learning.

Ansible is an open-source configuration management tool. used for IT tasks such as configuration management, application deployment, in-service orchestration, and provisioning. This is an easy task to set up this highly efficient and powerful tool. This is a free tool that can run on multiple operating systems like MAC, Linux, etc. Apart from the free version, there is one enterprise version to that is named Ansible Tower, and it is generally used to enjoy maximum benefits by industries. And Ansible is rapidly rising to the top in the world of automation tools.

Why Ansible ?

  • It is a free open source application

  • Agent-less – No need for agent installation and management

  • Phython/yaml based

  • Highly flexible and configuration management of systems.

  • Large number of ready to use modules for system management

  • Custom modules can be added if needed

  • Configuration roll-back in case of error

  • Simple and human readable

  • Self documenting

Installation of Ansible

Create a Amazon Linux machine on AWS

# 1. Enable EPEL repository
sudo amazon-linux-extras enable epel

# 2. Install EPEL
sudo yum install -y epel-release

# 3. Install Ansible
sudo yum install -y ansible  

# 4. Verify Installation
ansible --version

# 5. You should see something like
ansible [core 2.18.7]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3/dist-packages/ansible
  ansible collection location = /home/root/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.12.3 (main, Jun 18 2025, 17:59:45) [GCC 13.3.0] (/usr/bin/python3)
  jinja version = 3.1.2
  libyaml = True

Ansible was installed, but default config and inventory files are not present. Then you need to create them manually or specify their location.

sudo mkdir -p /etc/ansible
sudo vi /etc/ansible/ansible.cfg

vi ansible.cfg

# Add 
[defaults]
inventory = /etc/ansible/hosts
host_key_checking = False
retry_files_enabled = False

Inventory File

sudo vi /etc/ansible/hosts

vi hosts

# Add
[local]
localhost ansible_connection=local

Test Ansible is working

ansible all -m ping

localhost | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Hosts :

The Ansible hosts file (inventory file) is a core component in automating IT tasks. Its main use case is to define which machines (hosts or groups) Ansible should manage or automate.

You can manage hundreds of servers from a single location.

You can group servers based on their roles (Ex. web, db, loadbalancer).

[web]
192.168.1.10
192.168.1.11

[db]
dbserver ansible_host=192.168.1.20 ansible_user=ubuntu

[loadbalancer]
ansible_ssh_private_key_file=~/.ssh/id_rsa
ansible_python_interpreter=/usr/bin/python3

Create a user in ansible :

Creating a user in Ansible is a very common task in infrastructure automation, especially in DevOps and system administration.

Why Create a User in Ansible ?

  • Standardized Access Across Servers

  • Security and Access Control

  • Automation Setup

  • User Management at Scale.

Create a Basic User

sudo adduser (username)

Then set a password :

sudo passwd (ansible)       # give any password.

Switch to the user :

su - (username)
sudo whoami

Allow Passwordless Sudo privileges :

sudo visudo

Add user to sudoers :

# User privilege specification
root    ALL=(ALL:ALL) ALL
ansible ALL=(ALL:ALL) ALL       # add your user below it. Example for a user named ansible

SSH Configuration :

sudo vi /etc/ssh/sshd_config
Port 22                 # Change port (default 22)
PermitRootLogin no      # Disable root login
PasswordAuthentication no   # Disable password login, allow only key-based
PubkeyAuthentication yes    # Enable key authentication

After making changes :

sudo systemctl restart sshd

Password-based Authentication :

You don't need to create an SSH key. Just ensure that the SSH server settings allow password-based login.

Connects using SSH with a username and password.

  • Quick to set up.

  • No keys needed.

vi /etc/ssh/sshd_config

PasswordAuthentication   Yes
PermitRootLogin      Yes

After that ,

systemctl restart sshd

SSH-key based Authentication :

Generate SSH key pair on the ansible control node, and copy the public key to the managed nodes.

  • Secure

  • No need to type a password every time.

  • Works well for automation.

On user

# ssh-keygen

Go to

 cd /home/ansible/.ssh

 ls

# you shoud get 
id_rsa  id_rsa.pub  known_hosts  known_hosts.old

# Private key = id_rsa
# Public key = id_rsa.pub

ssh-copy-id username@nodeip     # Copy the key to server

Ansible server :

# To connect to a node using SSH
ssh username@IP_address

Module :

Ansible modules are fundamental components of the Ansible automation engine . They are essentially small, self-contained programs or scripts that perform specific tasks on managed hosts.

A single unit of work in Ansible.

Is the one that actually performing execution.

ad-hoc :

An Ansible ad hoc command uses the /usr/bin/ansible command-line tool to automate a single task on one or more managed nodes. ad hoc commands are quick and easy, but they are not reusable

A quick, one-line Ansible command that runs a module without writing a playbook.

Use case of ad-hoc tasks :

ad-hoc tasks can be used to reboot servers, copy files, manage packages and users, and much more.

You can use any Ansible module in an ad-hoc task.

ad-hoc tasks, like playbooks, use a declarative model calculating and executing the actions required to reach a specified final state.

list all hosts in your Ansible inventory is :

 ansible all --list-hosts

# Output :
 hosts (3):
    localhost
    172.31.2.195
    172.31.14.107
ansible (group name) --list-hosts    (Specific group)

Ansible host pattern indexing :

Top-to-Bottom :

Bottom-to-Top

  • You can also count from the bottom by using negative indexing.

Example :

ansible (group name or all)[0] --list-hosts     # First host (n1)

ansible (group name or all)[1] --list-hosts     # Second host (n2)

ansible (group name or all)[-1] --list-hosts    # Last host (n4)

ansible (group name or all)[0:1] --list-hosts   # [start:end]

ansible (group name or all)[1:3] --list-hosts  # [start:end]

Listing files :

ansible (group or all) -a "ls"
ansible (group or all) -a "ls -l"
ansible (group or all) -a "ls -al"

Creating a file :

ansible (group or all) -a "touch insys"

Installing packages with ad-hoc commands :

ansible (group or all) -a "yum install httpd -y"

Runs the yum install directly :

ansible (group or all) -b -m yum -a "pkg=httpd state=present"

Removing packages :

ansible (group or all) -b -m yum -a "pkg=httpd state=absent"

Updating to latest version :

ansible (group or all) -b -m yum -a "pkg=httpd state=latest"

Managing services :

ansible (group or all) -b -m service -a "name=httpd state=started"
 
ansible (group or all) -b -m service -a "name=httpd state=stopped"

Create user :

ansible (group or all) -b -m user -a "name=ansible"

Playbook :

A YAML file that contains one or more plays.

YAML : human readable data serialization language.

YMAL Syntax :

string: Hello world !
number: 1
boolean: true

# list
tool:
    - Git
    - Ansible
    - Docker

# Dictionary 
name: Rohit
role: DevOps Engineer
skills:
  - AWS
  - Linux
  - Docker
  1. Hosts : inventory group or host

  2. User : Linux username

  3. Become : Run with root user.

  4. connection : connection type to the target machine. (ssh)

  5. Gather_facts : Ansible will collect system information (facts) about the target host (OS, IPs, CPU, RAM, etc.) before running tasks. (yes)

  6. Tasks : A list of actions to perform on the hosts.

  7. Handlers : Special tasks that only run when notified by other tasks.

Always starting with three hyphens (---) signals the start of a document.

---
- name: Install and configure Nginx
  hosts: demo
  become: yes
  tasks:
    - name: Ensure Nginx is installed
      yum:
        name: nginx
        state: present
      notify: Restart nginx  # This notifies the handler to restart Nginx

    - name: Copy custom Nginx configuration
      copy:
        src: /home/ansible/nginx.conf
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted  # The handler will restart Nginx if notified

Dry run : In Ansible, a dry run means running your playbook without actually making any changes to the target systems.

ansible-playbook playbook.yml --check

Ansible vault :

Ansible vault lets you encrypt YAML files, strings, or variables used in playbooks, inventories, or role defaults/vars. You can then decrypt them on-the-fly when running playbooks.

Create an encrypted file.

ansible-vault create filename.yml

New Vault password:                    # give password
Confirm New Vault password:            # rewrite password

Encrypt an existing file

ansible-vault encrypt filename.yml

New Vault password:                  # give password
Confirm New Vault password:          # rewrite password
Encryption successful

View contents of an encrypted file

ansible-vault view filename.yml

Vault password:           # give password

Edit an encrypted file

ansible-vault edit filename.yml

Vault password:           # give password

Decrypt a file (make it plaintext)

ansible-vault decrypt filename.yml

Vault password:            # give password
Decryption successful

Run a playbook using vault-encrypted files

ansible-playbook filename.yml --ask-vault-pass

Use a password file instead of typing each time

ansible-playbook filename.yml --vault-password-file /path/to/pass.txt

# Ex..
ansible-playbook vault.yml vault-password-file pass.txt

What is an Ansible Role ?

An Ansible role is a way to organize your playbooks and automation code into a structured, reusable format.
Instead of writing everything in one long playbook, you break it into smaller, logical units (roles).

Main Components of an Ansible Role :

  1. tasks/

    • Contains the main list of tasks (YAML files) the role performs.

    • The default entry point is main.yml.

    • Example: Installing packages, starting services.

  2. handlers/

    • Contains handlers triggered by tasks (like restarting a service after a config change).

    • Default file: main.yml.

  3. templates/

    • Holds Jinja2 template files (.j2) for configuration files.

    • These templates can dynamically use variables.

  4. files/

    • Static files (binaries, configs, scripts) that can be copied to managed nodes.
  5. vars/

    • Stores role-specific variables with high precedence.

    • Default file: main.yml.

  6. defaults/

    • Stores role default variables with lowest precedence.

    • Useful for providing safe default values.

  7. meta/

    • Defines metadata about the role (dependencies on other roles, author info, license, etc.).

    • Default file: main.yml.

  8. tests/

    • Contains sample playbooks and inventory for testing the role.
  9. README.md (optional but recommended)

    • Documentation about how to use the role.

Steps to Create a Role Manually :

Ansible roles have a standard folder structure.
Using tree, you can quickly check if everything is in the right place.

sudo apt install tree -y

Create the Role Directory

mkdir -p playbook/roles/give name of your role

cd /playbook/roles/give name of your role

Create Standard Subdirectories :

mkdir -p tasks handlers templates files vars defaults meta tests

Add Main Files :

touch tasks/main.yml
touch handlers/main.yml
touch vars/main.yml
touch defaults/main.yml
touch meta/main.yml
touch tests/test.yml

On playbook Create a master.yml file

vi master.yml
# Example...
# master.yml
- hosts: webservers
  become: true
  roles:
    - apache
    - mysql
    - security

Apply YML file :

ansible-playbook master.yml

Automate Role Creation :

ansible-galaxy init role_name

# This creates :
myrole/
├── defaults/main.yml
├── files/
├── handlers/main.yml
├── meta/main.yml
├── tasks/main.yml
├── templates/
├── tests/
└── vars/main.yml

You don’t need to manually create these directories/files.

Conclusion : Ansible stands out as a powerful and versatile automation tool that simplifies IT tasks such as configuration management, application deployment, and orchestration. Its open-source nature, agent-less architecture, and ease of use make it an attractive choice for both small-scale and enterprise-level operations. With a wide array of ready-to-use modules and the ability to create custom ones, Ansible offers flexibility and scalability. Its human-readable syntax and self-documenting capabilities further enhance its appeal, making it a preferred choice for DevOps and system administrators aiming to streamline their workflows and improve efficiency. As automation continues to play a crucial role in IT, Ansible's role in facilitating seamless and efficient operations is undeniable.