DEV Community

Cover image for Getting Started with Ansible: A Complete Guide to IT Automation
Osagie Anolu
Osagie Anolu

Posted on

Getting Started with Ansible: A Complete Guide to IT Automation

Image description

Ansible is a powerful open-source automation tool that can help you manage servers, configure systems, and deploy applications at scale. In this comprehensive guide, we'll explore everything you need to know to get started with Ansible.

What is Ansible?

Ansible is an agentless automation platform that simplifies:

  • Configuration Management
  • Application Deployment
  • Task Automation
  • IT Orchestration
  • Cloud Provisioning

Unlike other configuration management tools, Ansible doesn't require any special software to be installed on the nodes it manages. It uses SSH for secure connections and Python for executing its modules.

Why Choose Ansible?

  1. Agentless Architecture: No need to install special software on managed nodes
  2. Simple Syntax: Uses YAML, which is human-readable and easy to learn
  3. Idempotent: Running the same playbook multiple times won't change the result
  4. Large Community: Extensive collection of pre-built modules and roles
  5. Push-Based: Changes are pushed from a central location

Installation and Setup

Installing Ansible

On Ubuntu/Debian:

sudo apt update
sudo apt install ansible
Enter fullscreen mode Exit fullscreen mode

On CentOS/RHEL:

sudo yum install epel-release
sudo yum install ansible
Enter fullscreen mode Exit fullscreen mode

On macOS:

brew install ansible
Enter fullscreen mode Exit fullscreen mode

Basic Configuration

The main Ansible configuration file is located at /etc/ansible/ansible.cfg. Here's a basic configuration:

[defaults]
inventory = ./inventory
remote_user = your_ssh_user
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
Enter fullscreen mode Exit fullscreen mode

Understanding Inventory Files

Inventory files define the hosts and groups that Ansible will manage. They can be in INI or YAML format.

Basic Inventory (inventory.ini)

[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com

[development]
dev.example.com ansible_host=192.168.1.100

[all:vars]
ansible_python_interpreter=/usr/bin/python3
Enter fullscreen mode Exit fullscreen mode

YAML Inventory (inventory.yml)

all:
  children:
    webservers:
      hosts:
        web1.example.com:
        web2.example.com:
    dbservers:
      hosts:
        db1.example.com:
        db2.example.com:
Enter fullscreen mode Exit fullscreen mode

Ad-Hoc Commands

Ad-hoc commands are one-line tasks that you can run against your hosts:

# Ping all servers
ansible all -m ping

# Check disk space
ansible webservers -a "df -h"

# Update apt cache (Ubuntu/Debian)
ansible webservers -m apt -a "update_cache=yes" --become
Enter fullscreen mode Exit fullscreen mode

Understanding Tasks

Tasks are the basic unit of work in Ansible. They define what actions should be performed.

Example task:

- name: Install nginx
  apt:
    name: nginx
    state: present
  become: yes

- name: Start nginx service
  service:
    name: nginx
    state: started
    enabled: yes
  become: yes
Enter fullscreen mode Exit fullscreen mode

Creating Playbooks

Playbooks are YAML files containing a list of plays. Each play is a set of tasks to be executed on specific hosts.

Basic Playbook (web_setup.yml)

---
- name: Configure web servers
  hosts: webservers
  become: yes

  tasks:
    - name: Install required packages
      apt:
        name: "{{ item }}"
        state: present
        update_cache: yes
      loop:
        - nginx
        - php-fpm
        - mysql-client

    - name: Copy nginx configuration
      template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

    - name: Start and enable services
      service:
        name: "{{ item }}"
        state: started
        enabled: yes
      loop:
        - nginx
        - php-fpm

  handlers:
    - name: Restart nginx
      service:
        name: nginx
        state: restarted
Enter fullscreen mode Exit fullscreen mode

Working with Variables

Variables in Ansible can be defined in multiple places:

In Playbooks

---
- hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
Enter fullscreen mode Exit fullscreen mode

In Variable Files (group_vars/webservers.yml)

---
http_port: 80
max_clients: 200
app_version: "1.2.3"
Enter fullscreen mode Exit fullscreen mode

Using Variables in Templates

# templates/nginx.conf.j2
server {
    listen {{ http_port }};
    root /var/www/html;

    location / {
        # configuration here
    }
}
Enter fullscreen mode Exit fullscreen mode

Roles

Roles are ways of automatically loading certain vars, files, tasks, handlers, and other Ansible artifacts based on a known file structure.

Role Directory Structure

roles/
  webserver/
    tasks/
      main.yml
    handlers/
      main.yml
    templates/
      nginx.conf.j2
    vars/
      main.yml
    defaults/
      main.yml
    meta/
      main.yml
Enter fullscreen mode Exit fullscreen mode

Using Roles in Playbooks

---
- hosts: webservers
  roles:
    - webserver
    - database
    - { role: app, vars: { app_port: 3000 } }
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Use Version Control

    • Keep your Ansible code in a git repository
    • Use meaningful commit messages
  2. Directory Structure

ansible-project/
├── inventory/
│   ├── production.yml
│   └── staging.yml
├── group_vars/
│   ├── all.yml
│   └── webservers.yml
├── roles/
│   └── webserver/
├── playbooks/
│   ├── site.yml
│   └── webserver.yml
└── ansible.cfg
Enter fullscreen mode Exit fullscreen mode
  1. Tags
    • Use tags to run specific parts of your playbooks
tasks:
  - name: Install packages
    apt:
      name: nginx
      state: present
    tags: ['packages', 'nginx']
Enter fullscreen mode Exit fullscreen mode
  1. Vault
    • Use ansible-vault for sensitive data
# Encrypt file
ansible-vault encrypt secrets.yml

# Edit encrypted file
ansible-vault edit secrets.yml
Enter fullscreen mode Exit fullscreen mode

Common Modules

  1. File Operations
- name: Create directory
  file:
    path: /app/data
    state: directory
    mode: '0755'

- name: Copy file
  copy:
    src: files/app.conf
    dest: /etc/app/app.conf
Enter fullscreen mode Exit fullscreen mode
  1. Package Management
- name: Install packages
  package:
    name: "{{ item }}"
    state: present
  loop:
    - git
    - curl
    - vim
Enter fullscreen mode Exit fullscreen mode
  1. Service Management
- name: Ensure service is running
  service:
    name: nginx
    state: started
    enabled: yes
Enter fullscreen mode Exit fullscreen mode

Debugging

  1. Verbose Output
ansible-playbook playbook.yml -vvv
Enter fullscreen mode Exit fullscreen mode
  1. Debug Module
- name: Debug variable
  debug:
    var: http_port
    msg: "The HTTP port is {{ http_port }}"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Ansible is a powerful tool for automation that can significantly improve your infrastructure management workflow. This tutorial covered the basics, but there's much more to explore, including:

  • Dynamic inventory
  • Custom modules
  • Error handling
  • Conditionals and loops
  • Advanced playbook features

Remember to always test your playbooks in a staging environment before running them in production.

Additional Resources

Top comments (0)