Part 4 ยท Chapter 13

Ansible: Teaching Robots to Set Up Rooms

Automate server configuration โ€” install software, manage files, run commands across dozens of servers at once.

What you'll learn in this chapter

  • What Ansible is and the problem it solves (configuring many servers consistently)
  • The key difference between Ansible and Terraform โ€” and why you often need both
  • Ansible's core vocabulary: inventory, playbook, task, module, role, handler, vault
  • How to write an inventory file and your first playbook from scratch
  • Jinja2 templates for dynamic configuration files
  • Organizing complex projects with Ansible roles
  • Protecting secrets with Ansible Vault
  • How Ansible compares to Puppet and Chef

The Robot Butler Analogy

Imagine you manage a hotel with 50 rooms. Before every guest checks in, each room must be prepared: fresh towels folded precisely on the rack, a mint on the pillow, the TV set to the welcome channel, the air conditioning at exactly 22ยฐC, and the complimentary notepad placed at a 45-degree angle on the desk. (This hotel has standards.)

You could walk through all 50 rooms yourself. It would take hours, be exhausting, and you'd almost certainly miss something in room 37. Or you could hire a robot butler. You write the instructions once โ€” precisely, in a format the robot understands. Hand the robot the list of rooms and the instructions. The robot visits every room in order, checks what needs doing, does it, and reports back: "All 50 rooms ready. Three towel racks were already correct. 47 mints were placed."

Ansible is that robot butler โ€” but for servers instead of hotel rooms. You write instructions (called playbooks) in simple YAML. Ansible connects to all your servers via SSH and carries out those instructions. No special software needs to be installed on the servers first. As long as Ansible can SSH in, it can configure the machine.

๐Ÿค– Agentless โ€” The Killer Feature

One of Ansible's most important properties is that it is agentless. Tools like Puppet and Chef require you to install a daemon (a background agent process) on every server you want to manage. That agent then "phones home" to a central server for instructions. This creates complexity โ€” you have to manage the agent itself, its certificates, its upgrades.

Ansible doesn't work this way. It uses SSH โ€” the same secure shell protocol you already use to log into servers. Ansible connects, runs Python commands, disconnects. Nothing left behind. This means you can start managing a brand new server immediately, with zero preparation, as long as you have SSH access.

Terraform vs Ansible โ€” What's the Difference?

This is one of the most commonly asked questions in DevOps, and it has a clear answer. These tools solve different problems. Using both together is the most powerful approach.

The Division of Labor

Terraform: "Build the building"
Creates infrastructure: EC2 instances, VPCs, RDS databases, S3 buckets, load balancers

Ansible: "Set up the building"
Configures servers: installs software, copies config files, creates users, starts services

Together: Terraform provisions the servers โ†’ Ansible configures them โ†’ app deployed

Think of it this way: Terraform builds the apartment building. Ansible furnishes and decorates the apartments. You need both โ€” an empty building isn't useful, and a beautifully furnished apartment that doesn't exist isn't either.

๐Ÿ“– Ansible Core Vocabulary
  • Inventory: the list of servers Ansible knows about โ€” IP addresses or hostnames, organized into groups
  • Playbook: a YAML file containing one or more plays โ€” the top-level instruction document you run
  • Play: a mapping of tasks to a group of hosts. "Run these tasks on all web servers."
  • Task: a single action โ€” install this package, create this file, restart this service
  • Module: Ansible's pre-built actions. apt, yum, copy, template, service, user, git, docker_container โ€” hundreds of them, one for almost everything you'd ever need to do on a server
  • Handler: a special task that only runs when explicitly triggered. The classic example: "Restart Nginx only if the config file actually changed."
  • Role: a reusable, organized collection of tasks, files, templates, and variables packaged in a standard directory structure
  • Vault: Ansible's encrypted secrets store โ€” passwords and API keys live here, encrypted at rest

The Inventory โ€” Who Are You Talking To?

Before Ansible can do anything, it needs to know which servers to work with. That's the inventory. Think of it like an address book: "These are my web servers. These are my database servers. Here's how to SSH into each one."

Inventories can be in INI format (old school, simple) or YAML format (modern, more flexible):

INI Inventory (hosts.ini)

# hosts.ini โ€” classic INI format
[web]
web1.example.com
web2.example.com
192.168.1.10

[database]
db1.example.com

[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/my-key.pem

YAML Inventory (inventory.yml) โ€” Preferred Modern Format

# inventory.yml โ€” modern YAML format
all:
  children:
    web:
      hosts:
        web1.example.com:
        web2.example.com:
    database:
      hosts:
        db1.example.com:
  vars:
    ansible_user: ubuntu
    ansible_ssh_private_key_file: ~/.ssh/my-key.pem

Ad-Hoc Commands โ€” Quick One-Liners

Before writing a full playbook, you can run quick one-liner commands against your inventory. These are called ad-hoc commands โ€” great for checking connectivity or running emergency fixes:

# Test connectivity to all hosts (like ping)
ansible all -i hosts.ini -m ping

# Run a shell command on all web servers
ansible web -i hosts.ini -m shell -a "df -h"

# Install nginx on web servers (--become = sudo)
ansible web -i hosts.ini -m apt -a "name=nginx state=present" --become

# Restart a service
ansible web -i hosts.ini -m service -a "name=nginx state=restarted" --become

# Check uptime on all hosts
ansible all -i hosts.ini -a "uptime"

Your First Playbook โ€” Setting Up a Web Server

Ad-hoc commands are useful for quick tasks, but for anything serious you write a playbook. The following playbook configures a complete Nginx web server setup โ€” updating packages, installing software, creating directories, copying configuration, and starting services. Notice how readable the YAML is โ€” even a non-engineer can understand roughly what it does:

---
# setup-webserver.yml
- name: Configure web servers
  hosts: web
  become: true   # run all tasks as sudo

  vars:
    app_user: www-data
    app_dir: /var/www/myapp
    nginx_port: 80

  tasks:
    - name: Update apt package cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install required packages
      apt:
        name:
          - nginx
          - curl
          - git
        state: present

    - name: Create application directory
      file:
        path: "{{ app_dir }}"
        state: directory
        owner: "{{ app_user }}"
        mode: '0755'

    - name: Copy nginx configuration from template
      template:
        src: nginx.conf.j2
        dest: /etc/nginx/sites-available/myapp
      notify: Reload nginx      # triggers handler if this task makes a change

    - name: Enable nginx site (create symlink)
      file:
        src: /etc/nginx/sites-available/myapp
        dest: /etc/nginx/sites-enabled/myapp
        state: link
      notify: Reload nginx

    - name: Ensure nginx is started and enabled at boot
      service:
        name: nginx
        state: started
        enabled: yes

  handlers:
    - name: Reload nginx
      service:
        name: nginx
        state: reloaded
๐Ÿ’ก Idempotency โ€” Run It a Hundred Times, Same Result

Notice the task says state: present rather than "install nginx." This is intentional. Ansible modules are designed to be idempotent โ€” if nginx is already installed, running the task again does nothing. It won't install it twice, break anything, or report an error. This means you can run your playbook against a server repeatedly โ€” to verify configuration, to apply updates, or to onboard new servers โ€” without fear of side effects.

Handlers โ€” Only Run When Needed

Notice the notify: Reload nginx in the tasks above, and the handlers: section at the bottom. Here's the key insight: the handler only fires if the task that notified it actually changed something.

If your Nginx config file is already correct (no changes needed), the template task won't notify the handler, and Nginx won't be reloaded. This avoids unnecessary service restarts โ€” restarting Nginx briefly drops connections, so you only want to do it when you actually changed its config. The handler also only fires once, even if notified by multiple tasks.

Jinja2 Templates โ€” Dynamic Config Files

Static config files are limited. What if you need the config file to contain the server's own hostname? Or a variable that's different in staging versus production? Ansible uses Jinja2 templates โ€” files with {{ variable }} placeholders that Ansible fills in before copying.

The nginx template referenced in the playbook above:

# templates/nginx.conf.j2 โ€” Jinja2 template
server {
    listen {{ nginx_port }};
    server_name {{ inventory_hostname }};   # Ansible fills this in automatically

    access_log /var/log/nginx/{{ inventory_hostname }}_access.log;
    error_log  /var/log/nginx/{{ inventory_hostname }}_error.log;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # Add SSL location if in production
    {% if environment == 'production' %}
    listen 443 ssl;
    ssl_certificate /etc/ssl/certs/myapp.crt;
    ssl_certificate_key /etc/ssl/private/myapp.key;
    {% endif %}
}

Ansible Roles โ€” Organized Playbooks for Real Projects

A single playbook file works fine for small projects. But once you're managing web servers, database servers, monitoring agents, and application deployments, a single file becomes unwieldy. Ansible roles solve this with a standard directory structure โ€” like how a well-organized kitchen has a place for everything, and everything is in its place.

Standard Role Directory Structure

roles/
  webserver/
    tasks/main.yml       โ† the task definitions
    handlers/main.yml   โ† handler definitions
    templates/         โ† Jinja2 template files (.j2)
    files/             โ† static files to copy to servers
    defaults/main.yml   โ† default variable values
    vars/main.yml      โ† role-specific variable overrides
    meta/main.yml      โ† role metadata and dependencies

Using roles makes your playbooks beautifully simple:

---
# site.yml โ€” applies roles to host groups
- hosts: web
  roles:
    - common        # baseline setup for all servers
    - webserver     # nginx + app directory
    - nodejs        # Node.js runtime
    - monitoring    # Prometheus node exporter

- hosts: database
  roles:
    - common
    - postgresql
    - monitoring
๐ŸŒŸ Ansible Galaxy

Just like Terraform has the Registry, Ansible has Galaxy (galaxy.ansible.com) โ€” a community repository of pre-built roles for almost every common task: installing PostgreSQL, setting up Docker, configuring firewalls, deploying Java apps, setting up monitoring. Before writing a role from scratch, check Galaxy. The community roles often handle edge cases you haven't thought of yet.

Install a role from Galaxy: ansible-galaxy install geerlingguy.nginx

Ansible Vault โ€” Protecting Secrets

Here's a problem: your playbooks need passwords. Database passwords, API keys, TLS certificates. But you can't just put them in plain text in a YAML file that's checked into Git. Anyone with repo access โ€” or anyone who ever gets access โ€” would see all your secrets.

Ansible Vault solves this elegantly. It encrypts files (or individual values) using AES-256 encryption. The encrypted content is stored safely in Git. To run the playbook, you provide the vault password โ€” either interactively or from a password file. No secrets in plain text, ever.

# Create a new encrypted secrets file
ansible-vault create secrets.yml

# Encrypt an existing file
ansible-vault encrypt secrets.yml

# View the contents of an encrypted file
ansible-vault view secrets.yml

# Edit an encrypted file (opens in your $EDITOR)
ansible-vault edit secrets.yml

# Run a playbook that uses vault-encrypted files
ansible-playbook site.yml --ask-vault-pass

# Or use a vault password file (great for CI/CD)
ansible-playbook site.yml --vault-password-file .vault-pass

An encrypted secrets.yml looks like this in Git โ€” completely unreadable without the vault password:

$ANSIBLE_VAULT;1.1;AES256
61333363313931313263353661346135613661356332376361343161623961393736336364383335
35383362393365303362383431323161336536373435373663353436333039323530376261373335
...

Running the Playbook โ€” Day-to-Day Commands

Once your playbooks are written, these are the commands you'll use every day:

# Check syntax before running (catches YAML errors)
ansible-playbook setup-webserver.yml --syntax-check

# Dry run โ€” show what WOULD change without making any changes
ansible-playbook setup-webserver.yml --check --diff

# Run against your full inventory
ansible-playbook -i inventory.yml setup-webserver.yml

# Run against only specific hosts (useful for testing on one server first)
ansible-playbook setup-webserver.yml --limit web1.example.com

# Run only tasks with specific tags
ansible-playbook setup-webserver.yml --tags "nginx,ssl"

# Skip tasks with specific tags
ansible-playbook setup-webserver.yml --skip-tags "slow-tasks"

# Pass extra variables on the command line
ansible-playbook setup-webserver.yml -e "environment=production nginx_port=8080"

# Increase verbosity for debugging (-v, -vv, -vvv)
ansible-playbook setup-webserver.yml -vv
๐Ÿ’ก The --check --diff Combo

Running with --check --diff before a real run is one of the best habits in Ansible. --check runs the playbook in "dry run" mode โ€” no changes are made. --diff shows you exactly what lines in files would be changed, like a git diff. Together, you can see precisely what Ansible is about to do before it does it. Review the diff, then run without the flags to apply.

A Complete Application Deployment Playbook

Here's a more complete real-world example โ€” deploying a Node.js application from a Git repository:

---
# deploy-app.yml
- name: Deploy application
  hosts: web
  become: true

  vars_files:
    - secrets.yml   # ansible-vault encrypted

  vars:
    app_repo: https://github.com/myorg/myapp.git
    app_dir: /var/www/myapp
    node_version: "20"

  tasks:
    - name: Install Node.js {{ node_version }}
      shell: |
        curl -fsSL https://deb.nodesource.com/setup_{{ node_version }}.x | bash -
        apt-get install -y nodejs
      args:
        creates: /usr/bin/node   # skip if already installed

    - name: Clone or update application repository
      git:
        repo: "{{ app_repo }}"
        dest: "{{ app_dir }}"
        version: main
        force: yes
      notify: Restart application

    - name: Install npm dependencies
      npm:
        path: "{{ app_dir }}"
        production: yes

    - name: Write environment configuration
      template:
        src: env.j2
        dest: "{{ app_dir }}/.env"
        mode: '0600'
      notify: Restart application

    - name: Ensure PM2 process manager is installed
      npm:
        name: pm2
        global: yes

    - name: Start application with PM2
      command: pm2 start ecosystem.config.js --env production
      args:
        chdir: "{{ app_dir }}"
        creates: "{{ app_dir }}/.pm2-started"

  handlers:
    - name: Restart application
      command: pm2 restart all
      become_user: www-data

Ansible vs Puppet vs Chef

Ansible entered a market that already had Puppet (2005) and Chef (2009). All three solve the same problem โ€” configuration management at scale. Here's how they differ:

๐Ÿ“– Configuration Management Tools Compared
  • Ansible: Agentless (uses SSH). YAML playbooks. Push-based (you run it). Easiest to learn and get started. Excellent for most use cases. The clear first choice for teams starting out.
  • Puppet: Requires a Puppet agent on every server. Declarative DSL (custom language). Pull-based (agents pull config from Puppet server). Very mature, excellent for large enterprises. Steeper learning curve.
  • Chef: Requires a Chef client on every server. Recipes written in Ruby (a real programming language). Pull-based. More flexible than Puppet for complex logic. Steep learning curve โ€” you effectively need to know Ruby.
  • SaltStack: Agent-based but can work agentless. YAML and Jinja2 (similar to Ansible). Push or pull. Faster than Ansible for very large fleets. Less popular outside large-scale deployments.

For any team that doesn't already have Puppet or Chef, start with Ansible. It's the fastest to learn, requires no agents, and handles every production use case we've seen in this book.

Chapter Summary

  • Ansible is a configuration management tool that connects to servers via SSH (agentless) and runs instructions from YAML files called playbooks.
  • Terraform and Ansible complement each other: Terraform builds infrastructure, Ansible configures it. Use both in sequence.
  • The core concepts are: inventory (server list), playbook (instruction file), task (single action), module (pre-built action), handler (conditional task), role (organized reusable collection), and vault (encrypted secrets).
  • Ansible modules are idempotent โ€” running the same playbook twice produces the same result, with no unintended side effects.
  • Handlers only fire when triggered by a task that actually made a change โ€” preventing unnecessary service restarts.
  • Jinja2 templates allow dynamic configuration files with variables, conditionals, and loops.
  • Ansible Vault protects secrets with AES-256 encryption, allowing you to safely commit encrypted credentials to Git.
  • Use --check --diff before every run to preview what will change โ€” it's the Ansible equivalent of terraform plan.