Ansible on Ubuntu Tutorial: Automated Multi-Server Management

Ubuntu tutorial - IT technology blog
Ubuntu tutorial - IT technology blog

The Real-World Problem: When Manual Administration Hits Its Limit

Managing two or three servers is easy enough. You just open a terminal, run a few package update commands, or tweak an Nginx configuration file, and you are done. But once your infrastructure expands to 15, 30, or 50 VPS instances, the story changes completely.

When a severe OpenSSL security vulnerability dropped, I had to patch a cluster of 25 servers urgently. The workflow was exhausting and repetitive: SSH into node 1, run commands, verify; disconnect, move to node 2… By server 8, I accidentally typed a typo space in an Nginx config. The website crashed instantly. I wasted 45 minutes in sheer panic just figuring out which machine had the error.

Manual operations consistently bring three major traps:

  • Wasted Time: Repetitive tasks consume your entire workday. A basic update routine across 30 machines can easily eat up half a day.
  • Inevitable Human Error: Performing the exact same sequence on 20 servers makes it all too easy to skip a command or forget restarting a service on a few of them.
  • Configuration Drift: After a few months in production, configurations between Staging and Production start to diverge. Nobody can say for sure whether all nodes remain consistent.

Why Manual Management Fails to Scale

The root problem lies in treating servers like “Pets” rather than “Cattle”. You remember the name of every VPS and handcraft individual configuration files.

This paradigm collapses when scaling up infrastructure for three core reasons:

  1. Lack of Idempotency: Plain shell scripts work fine the first time, but running them a second time often causes errors. A script might append duplicate lines to a config file or restart services unnecessarily.
  2. Lost Audit Trails (IaC): Commands are scattered across the bash history of separate machines. Anyone stepping in to take over will have no idea what changes were made to the system.
  3. Middleware Overhead: Legacy automation platforms often require installing background agents on every target machine. This burns unnecessary RAM and expands the security attack surface.

Three Common Approaches for Sysadmins

When solving configuration synchronization, we typically have three choices:

1. Writing Bash Scripts with SSH Loops

The most familiar workaround: gather IP addresses in a file and run a for loop over SSH.

Pros: Fast, leverages existing built-in tools.
Cons: Brittle. If the network drops on the 5th server, the script halts abruptly or skips nodes with no rollback mechanism. Once logic becomes complex, Bash scripts become a nightmare to maintain.

2. Using Agent-Based Tools (Puppet, Chef)

Requires a centralized Master server and dedicated background agents installed on every target node.

Pros: Strict policy management, automatic periodic configuration pulls.
Cons: Overkill for setups under 50 nodes. You have to manage SSL certificates, sacrifice 100-200MB of RAM per agent, and handle periodic agent version upgrades.

3. Choosing Ansible (The Agentless Model)

Ansible takes a minimalist approach: zero agents installed on target nodes. The control machine connects to target hosts over standard SSH and utilizes the Python runtime already built into Ubuntu.

Hands-On Ansible on Ubuntu: From Installation to a Full Playbook

Here is the practical workflow I use to standardize configurations across a fleet of 20 VPS instances running Ubuntu 22.04 LTS.

Step 1: Install Ansible on the Control Node

Install Ansible on your local machine (Ubuntu/WSL) or a dedicated management VPS:

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

Step 2: Configure Passwordless SSH Key Authentication

Always use SSH keys instead of storing plaintext passwords in configuration files:

# Generate an Ed25519 key if you do not already have one
ssh-keygen -t ed25519 -C "ansible-admin"

# Copy the public key to managed nodes (replace IPs and usernames accordingly)
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]
ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]

Step 3: Define Inventory and Test Connectivity

Initialize a project directory and create the hosts.ini file:

mkdir ~/ansible-lab && cd ~/ansible-lab
nano hosts.ini

Define your target server inventory:

[webservers]
web1 ansible_host=192.168.1.101
web2 ansible_host=192.168.1.102

[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_ed25519
ansible_python_interpreter=/usr/bin/python3

Test connectivity using the ping module:

ansible -i hosts.ini all -m ping

When the output returns green with "ping": "pong" and a status of SUCCESS, your nodes are ready to accept commands.

Step 4: Write a Playbook to Standardize the Environment

The core superpower of a Playbook is Idempotency. Whether executed once or ten times, the end state remains identical.

Create a file named setup-system.yml to update the OS, configure the timezone, and install essential packages:

---
- name: Standardize baseline configuration for Ubuntu systems
  hosts: webservers
  become: true
  tasks:
    - name: Update apt cache and upgrade system packages
      ansible.builtin.apt:
        update_cache: true
        upgrade: dist
        cache_valid_time: 3600

    - name: Synchronize timezone to Asia/Ho_Chi_Minh
      community.general.timezone:
        name: Asia/Ho_Chi_Minh

    - name: Install mandatory utility packages
      ansible.builtin.apt:
        name:
          - curl
          - htop
          - git
          - ufw
        state: present

    - name: Install Nginx web server
      ansible.builtin.apt:
        name: nginx
        state: present

    - name: Start and enable Nginx on boot
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

Execute the Playbook with the following command:

ansible-playbook -i hosts.ini setup-system.yml

Ansible executes tasks concurrently across all nodes. For packages or configurations already in place (like curl), it flags them as ok (in green) and skips them. Any task applying fresh modifications reports as changed (in yellow).

Production Optimization Tips

  • Perform dry-runs with --check: Before running directly in Production, use ansible-playbook -i hosts.ini setup-system.yml --check. This dry-run mode previews changes without modifying system state.
  • Encrypt Secrets with Ansible Vault: Never commit credentials or private keys to Git. Use ansible-vault encrypt secret.yml to safeguard sensitive variable files.
  • Enable SSH Pipelining for Performance: Create an ansible.cfg file in the same directory as your inventory to slash SSH round-trip overhead. This often cuts playbook execution time in half:
[defaults]
inventory = hosts.ini
host_key_checking = False
forks = 10

[ssh_connection]
pipelining = True

Investing 30 minutes to configure Ansible upfront will save you hundreds of hours of manual, repetitive work later. Scaling your infrastructure from 5 to 50 servers simply becomes a matter of adding a few IP addresses to your inventory file.

Share: