How to Automate Tasks with Ansible: A Step-by-Step Guide

Arijit DasArijit Das
4 min read

1. Introduction

Ansible is an open-source automation tool for configuration management, application deployment, and task automation. It uses a simple YAML-based language (called Playbooks) and operates agentlessly over SSH or WinRM.

2. Why Ansible?

  • Agentless: No software/agent installation needed on clients.

  • Simple YAML Syntax: Easy to learn and write.

  • Idempotency: Ensures operations are safe and repeatable.

  • Large Community: Extensive module support and reusable roles via Ansible Galaxy.

  • Scalable: Works for small systems to complex infrastructures.

3. Core Concepts

  • Controller Node: The machine where Ansible is installed and run.

  • Managed Nodes: Remote systems Ansible manages.

  • Inventory: A file that lists managed hosts.

  • Modules: Reusable scripts (e.g., copy, yum, service).

  • Playbooks: YAML files that define a set of plays/tasks.

  • Roles: Predefined directory structure for organizing Playbooks.

4. Ansible Architecture

+-------------------+
|  Ansible Control  |
|      Node         |
+--------+----------+
         |
         | SSH / WinRM
         v
+--------+----------+
|   Managed Nodes   |
| (Linux / Windows) |
+-------------------+

5. Installation

On Ubuntu/Debian:

sudo apt update
sudo apt install ansible -y

On CentOS/RHEL:

sudo yum install epel-release -y
sudo yum install ansible -y

Via pip:

pip install ansible

6. Ansible Inventory

Default location: /etc/ansible/hosts

Example (INI):

[web]
web1.example.com
web2.example.com

[db]
db1.example.com ansible_user=admin ansible_port=2222

YAML Inventory (new-style):

all:
  hosts:
    server1:
    server2:
  children:
    web:
      hosts:
        server1:
    db:
      hosts:
        server2:

7. Modules

Ansible ships with hundreds of modules.

Examples:

ModulePurpose
pingCheck connectivity
copyCopy files
yum / aptInstall packages
serviceManage services
userManage users

Example:

ansible all -m ping

8. Ad-Hoc Commands

Quick tasks without a playbook.

ansible web -m shell -a "uptime"
ansible db -m yum -a "name=httpd state=latest"

9. Playbooks

Written in YAML format.

Example:

- name: Install Nginx
  hosts: web
  become: yes
  tasks:
    - name: Install nginx
      apt:
        name: nginx
        state: present

    - name: Start nginx
      service:
        name: nginx
        state: started
        enabled: yes

Run with:

ansible-playbook nginx.yml

10. Roles

Standardized directory structure:

roles/
└── nginx/
    ├── tasks/
    │   └── main.yml
    ├── handlers/
    ├── templates/
    ├── files/
    ├── vars/
    └── defaults/

Use in playbook:

roles:
  - nginx

11. Variables and Facts

Defining Variables:

  • In playbooks: vars

  • From files: vars_files

  • From inventory

  • Gathered facts (system info)

vars:
  pkg_name: nginx

tasks:
  - name: Install web server
    apt:
      name: "{{ pkg_name }}"
      state: present

12. Templates (Jinja2)

Dynamic file generation.

Example: nginx.conf.j2:

server {
  listen 80;
  server_name {{ server_name }};
}

Usage in playbook:

- name: Template config
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf

13. Conditionals and Loops

Conditionals:

- name: Install Nginx
  apt:
    name: nginx
    state: present
  when: ansible_os_family == "Debian"

Loops:

- name: Create users
  user:
    name: "{{ item }}"
    state: present
  loop:
    - alice
    - bob

14. Handlers and Notifications

tasks:
  - name: Change config
    template:
      src: nginx.conf.j2
      dest: /etc/nginx/nginx.conf
    notify:
      - restart nginx

handlers:
  - name: restart nginx
    service:
      name: nginx
      state: restarted

15. Tags

Run specific tasks only.

- name: Install nginx
  apt:
    name: nginx
    state: present
  tags: install

Run with:

ansible-playbook site.yml --tags install

16. Error Handling

- name: Try something
  command: /bin/false
  ignore_errors: yes

Or use block, rescue, always:

- block:
    - name: Fail
      command: /bin/false
  rescue:
    - name: Recover
      debug:
        msg: "Something went wrong"

17. Vault (Secrets Management)

Encrypt secrets like passwords.

ansible-vault encrypt secrets.yml
ansible-vault decrypt secrets.yml
ansible-playbook site.yml --ask-vault-pass

18. Best Practices

  • Use roles to organize code.

  • Don’t hardcode passwords or IPs.

  • Use version control (e.g., Git).

  • Group similar hosts.

  • Test with --check.

19. Ansible Galaxy

A repository of community-maintained roles.

ansible-galaxy install geerlingguy.nginx

Use in playbook:

roles:
  - geerlingguy.nginx

20. Ansible Tower / AWX

Web-based GUI and REST API for managing Ansible.

  • AWX: Open-source upstream version.

  • Features:

    • Role-based access

    • Real-time output

    • Scheduling

    • Inventory sync

21. Common Use Cases

  • Server provisioning

  • Configuration management

  • CI/CD workflows

  • Application deployment

  • Cloud infrastructure setup (AWS, Azure, GCP)

22. Conclusion

Ansible is a powerful, agentless automation platform ideal for developers and sysadmins. Its ease of use and idempotent behavior make it suitable for managing everything from small applications to complex infrastructure across cloud and on-premises environments.

23. Appendices

Appendix A: Useful Commands

ansible --version
ansible-inventory --list -y
ansible all -m ping
ansible-playbook playbook.yml --check
ansible-vault view secrets.yml

Appendix B: Resources

0
Subscribe to my newsletter

Read articles from Arijit Das directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arijit Das
Arijit Das