Ansible Series

🛠️ A "Top 1%" Hands-On Lab: Automating Configuration Across Multiple Servers with Ansible

Introduction

This article is part of the Top 1% Series’ full article guide, and the second article in the Ansible Series.

Prerequisites

Prerequisites for This Hands-On Lab

Step 0: Installing Ansible on the Control Node

While logged into control over SSH, install Ansible itself.

sudo apt update
sudo apt install -y ansible

Once installed, check the version.

ansible --version

Alongside the version information, this also displays the Python version and the location of the config file. This tells you that Ansible itself is software implemented in Python, and that control needs its own Python runtime as well.

For what sudo apt update actually does under the hood (and why you run it before install every time, rather than out of habit), plus when to reach for sudo su - instead of prefixing every command with sudo, see Prep Manual: Initial Setup for an Ubuntu Server.

Step 1: Setting Up SSH Key Authentication

Ansible uses an SSH connection by default, but manually typing a password every run isn’t efficient and doesn’t suit automation, so set up SSH key authentication.

# Generate a key pair for the control user (skip if you already have one)
ssh-keygen -t ed25519

You can press Enter through every prompt to accept the defaults (leaving the passphrase empty is fine for this lab, though setting one is recommended in practice). Register the generated public key with node1.

ssh-copy-id <node1's username>@<node1's IP>

ssh-copy-id automatically appends the public key generated on control to node1’s ~/.ssh/authorized_keys. After running it, confirm you can log in without entering a password, with the following command.

Note: what ssh-keygen and ssh-copy-id are actually doing

ssh-keygen generates a mathematically paired private and public key on the spot. By default it creates two files: ~/.ssh/id_ed25519 (the private key) and ~/.ssh/id_ed25519.pub (the public key). If you want to use a different key pair for each of several servers from one control machine, you can create multiple key pairs by specifying a filename, e.g. ssh-keygen -f ~/.ssh/id_ed25519_node2.

What ssh-copy-id actually does is take the contents of the public key file you specify (or, if you omit any option, whichever public key sits at the default location, such as ~/.ssh/id_rsa.pub or ~/.ssh/id_ed25519.pub) and append it as a single line to the destination’s ~/.ssh/authorized_keys file over SSH. It does not copy “all your public keys at once” — it copies exactly one public key file. If you’re managing multiple key pairs, specify which public key to copy explicitly with the -i option, e.g. ssh-copy-id -i ~/.ssh/id_ed25519_node2.pub <username>@<IP>.

ssh <node1's username>@<node1's IP>
# If you can log in without being asked for a password, you're good. Then exit back to control
exit

Step 2: Writing an Inventory File

Create a working directory, and write an Inventory file listing the managed servers.

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

Write the following content (replace the IP address and username with your own environment’s).

[webservers]
node1 ansible_host=<node1's IP> ansible_user=<node1's username>

[webservers] is a group name — a unit for referring to multiple servers together. Here it’s just one server, but if you add a second managed VM, you can scale up simply by adding one more line inside the same [webservers] group.

ansible_host and ansible_user are reserved key names Ansible parses specially — misspell either by even one character (say, typing ansilbe_user instead of ansible_user), and Ansible silently treats it as an ordinary, ignored custom variable instead. With no username actually specified, Ansible falls back to connecting as whatever unintended user it defaults to (typically the local user running Ansible, or root). If you hit a connection error in the next step, check this file’s spelling character by character first.

Step 3: Checking Connectivity (the ping Module)

Confirm that Ansible can actually connect to the server listed in the Inventory.

ansible all -i inventory.ini -m ping

-m ping specifies Ansible’s ping module, not the ICMP ping command. It’s Ansible’s own module for confirming that the SSH connection and Python execution work correctly. Success looks like this:

node1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}

Getting back "ping": "pong" confirms that the SSH connection from control to node1, and its Python runtime, are working correctly.

Note: why "running Python" is part of how Ansible works at all

Ansible doesn’t just SSH into node1 — it actually executes a Python script on node1 itself. When the ansible.builtin.apt module installs Nginx, for example, Ansible transfers the Python script backing that module to node1 behind the scenes, runs it there with node1’s own Python interpreter, and gets back the result (whether it was already installed, or newly installed) as JSON. This step — actually running Python on node1 — is exactly what lets Ansible be more than an automated SSH command runner (a glorified shell script): it’s what makes idempotency possible, by checking the current state before deciding what, if anything, needs to change. The "discovered_interpreter_python": "/usr/bin/python3" you saw in the result above is Ansible reporting where it auto-detected the Python interpreter on node1. Since Ubuntu Server ships with Python 3 preinstalled, this all worked here with no extra setup.

Step 4: Writing a Playbook

Write a Playbook that installs Nginx, starts it, and deploys a simple test page.

nano site.yml
---
- name: Basic web server setup
  hosts: webservers
  become: true   # Run with administrator (sudo) privileges
  tasks:
    - name: Install Nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

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

    - name: Deploy a test page
      ansible.builtin.copy:
        content: "<h1>Hello from Ansible!</h1>\n"
        dest: /var/www/html/index.html

become: true declares that the whole set of Tasks should run with administrator (sudo) privileges. Each of the three Tasks — installing a package, starting a service, deploying a file — is an instance of the “state declaration” covered in the prerequisites article.

Step 5: Running the Playbook

ansible-playbook -i inventory.ini site.yml

If the user on node1 isn’t configured for passwordless sudo (NOPASSWD), this command fails with "msg": "Missing sudo password". That’s because become: true in the Playbook requires elevating to administrator privileges (sudo), but Ansible has no password to supply for it. In that case, run it with the -K (--ask-become-pass) option instead, which interactively prompts you for the sudo password.

ansible-playbook -i inventory.ini site.yml -K

Running it displays a color-coded changed or ok result for each Task. Since Nginx isn’t installed yet on the first run, all three Tasks should be reported as changed (yellow). The PLAY RECAP shown at the end gives you a summary like ok=4 changed=3.

Once it succeeds, check from control whether the test page is actually being served.

curl http://<node1's IP>/

If <h1>Hello from Ansible!</h1> comes back, the configuration pushed by the Playbook is actually in effect.

Step 6: Confirming Idempotency With Your Own Eyes

Now actually confirm the idempotency covered in the prerequisites article. Run the exact same Playbook again, without changing a single thing.

ansible-playbook -i inventory.ini site.yml

Check the result of this second run. This time, PLAY RECAP should show something like ok=4 changed=0. Confirm that all three Tasks — “Install Nginx,” “start it,” “deploy it” — are now reported as ok (already in the desired state), not changed. This is live proof that each of Ansible’s Modules internally guarantees idempotency.

Extra: Deliberately making a Playbook non-idempotent

To feel just how much idempotency matters, try adding a Task that uses the shell module to append to a file via a raw shell command, instead of the copy module.

    - name: (Bad example) Append to a file
      ansible.builtin.shell: echo "test" >> /var/www/html/index.html

Since this Task runs a raw shell command via the ansible.builtin.shell module, Ansible has no way to judge “is this already in the desired state?” As a result, it gets reported as changed every single time you run it, and you’ll see the file grow one more test line each time. This is a textbook example of a Task that doesn’t guarantee idempotency. In practice, when you do need shell or command, you have to manually compensate for idempotency yourself, using options like creates or changed_when.

Step 7: Cleaning Up

If you don’t plan to reuse these VMs for a later exercise, it’s fine to just leave the hands-on setup as it is. If you’d like to stop Nginx, you can write and run a Playbook for that on the spot, too.

---
- name: Stop Nginx
  hosts: webservers
  become: true
  tasks:
    - name: Stop Nginx and disable it on boot
      ansible.builtin.service:
        name: nginx
        state: stopped
        enabled: false

You’ll notice you’re already getting used to the idea of writing cleanup as a Playbook too, rather than SSHing into a server and manually running systemctl stop nginx.

Common Errors and How to Handle Them

Summary

What to Keep in Mind From Today

  1. After writing a Playbook, build the habit of always running it twice in a row and confirming the second run shows changed=0.
  2. Whenever you’re tempted to reach for the shell or command module, get in the habit of first checking whether a dedicated module exists (apt, service, copy, and so on) — a dedicated module automatically guarantees idempotency for you.

References

Comments

Feel free to leave thoughts, questions, or corrections below (sign in with a GitHub account to comment or react).