Deployn

Ansible for Beginners: Automate Servers From Scratch

Ansible from zero: install with pipx, inventory, first commands, playbooks, variables, templates and handlers, plus Docker and Uptime Kuma on two servers with one playbook.

Ansible for Beginners: Automate Servers From Scratch hero image
Contents
Tested with
ansible-core 2.22ansible-core 2.21Debian 13Ubuntu 24.04Uptime Kuma 2.5
Last checked on

If you set up a server by hand, you type the same commands again for the next one. Install updates, install tools, set the time zone, set up Docker. By the third server you forget a step. Ansible writes those steps into a file and runs them on as many servers as you like, as often as you like.

This guide starts at zero. At the end a single command sets up two servers with updates, a web server with its own start page, Docker and the monitoring app Uptime Kuma. I use Debian 13 and Ubuntu 24.04 as servers here and control them from a Linux machine.

Summary
  1. Install Ansible with pipx install --include-deps ansible.
  2. List the servers in inventory.ini and point ansible.cfg at it.
  3. Test the connection with ansible all -m ping.
  4. Write tasks into a playbook and run it with ansible-playbook.
  5. Use --check --diff to see what would change first.

How Ansible works

Ansible only runs on your machine. You install nothing on the servers; they only need SSH access and Python, and Debian and Ubuntu ship both. For every task Ansible sends a small Python program to the server over SSH, runs it and deletes it afterwards.

Diagram: the control node with inventory.ini, ansible.cfg and webserver.yml connects over SSH to the servers web1 (Debian 13) and web2 (Ubuntu 24.04)

A few terms come up all the time:

Term Meaning
Control node The machine Ansible runs on. Your PC or an admin server.
Managed node A server that Ansible manages.
Inventory The list of servers, usually sorted into groups.
Module A building block for one job, for example apt for packages or copy for files.
Task A module with parameters: “install nginx”.
Playbook A YAML file with tasks that run one after another.
Handler A task that only runs when another task changed something.
Fact A piece of information Ansible collects from the server, such as the OS or IP address.

One more word matters: idempotent. An Ansible task describes a target state, not a command. “nginx should be installed” instead of “install nginx”. If nginx is already there, Ansible does nothing. That’s why you can run a playbook as often as you want.

Prerequisites

Linux machine or WSLAnsible doesn’t run directly on Windows. On Windows you use WSL with Ubuntu, and the commands below are the same there.
One or two Debian or Ubuntu serversA VPS is enough. Two servers show better what Ansible does, but one works.
SSH key loginWith a user who can use sudo. I use the user {{server_user}}.

I created my test servers at Hetzner with the cloud-init generator: user admin, SSH key, sudo without a password. First check that you can log in from your machine:

Terminalbash
ssh {{server_user}}@{{web1_ip}}

On the first login SSH asks whether you trust the server’s fingerprint. Confirm with yes and log out with exit. Do this once for every server, otherwise Ansible gets stuck on exactly this question later.

Step 1: Install Ansible

The Ansible documentation recommends installing with pipx. It puts Ansible into its own Python environment, so nothing on your system gets mixed up.

Terminalbash
sudo apt update
sudo apt install -y pipx
pipx ensurepath

pipx ensurepath adds ~/.local/bin to your search path. For that to take effect, close the terminal and open a new one. Then install Ansible:

Terminalbash
pipx install --include-deps ansible

--include-deps makes sure that ansible-playbook and ansible-vault end up in the path too. Then check the version:

Terminalbash
ansible --version
ansible [core 2.22.0]
  config file = None
  ...
  python version = 3.13.5

The version you get depends on your system’s Python. On Debian 13 (Python 3.13) it was ansible-core 2.22, on Ubuntu 24.04 (Python 3.12) ansible-core 2.21. All playbooks in this guide ran with both.

Step 2: Project folder and inventory

An Ansible project is just a folder with text files. I create it in my home directory:

Terminalbash
mkdir ~/ansible-learn
cd ~/ansible-learn

The inventory lists the servers Ansible knows. A group name goes in square brackets, the servers below it:

inventory.iniini
[webserver]
web1 ansible_host={{web1_ip}}
web2 ansible_host={{web2_ip}}

[webserver:vars]
ansible_user={{server_user}}

web1 and web2 are names you choose. ansible_host tells Ansible which address the server has. The [webserver:vars] section applies to every server in the group, here for the login name.

So you don’t have to pass the inventory with every command, add a small config file:

ansible.cfgini
[defaults]
inventory = inventory.ini
interpreter_python = auto_silent

Ansible reads ansible.cfg from the folder you run the command in. interpreter_python = auto_silent lets Ansible find Python on the server by itself without printing a warning about it on every run.

Step 3: First commands

The first test is a ping. It isn’t a network ping but a module that logs in over SSH and checks that Python works:

Terminalbash
ansible all -m ping
web1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.13"
    },
    "changed": false,
    "ping": "pong"
}
web2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3.12"
    },
    "changed": false,
    "ping": "pong"
}

all means every server in the inventory, -m picks the module. Instead of all you can use the group name webserver or a single server like web1.

These one-off commands are called ad-hoc commands. Without -m, Ansible simply runs a command:

Terminalbash
ansible webserver -a "uptime"
web1 | CHANGED | rc=0 >>
 18:27:30 up 1 min,  1 user,  load average: 0.01, 0.01, 0.00
web2 | CHANGED | rc=0 >>
 18:27:30 up 1 min,  1 user,  load average: 0.13, 0.08, 0.03

You install a package with the apt module. That needs root rights, which Ansible gets via sudo with --become:

Terminalbash
ansible webserver -m ansible.builtin.apt -a "name=tree state=present" --become

The first time Ansible reports CHANGED because it installed tree. Run the same command again and you get SUCCESS with "changed": false. The package is already there, so there’s nothing to do.

Step 4: The first playbook

Ad-hoc commands are handy for quick questions. What should stay in place belongs in a playbook. The first one installs updates, a few tools and sets the time zone:

basics.ymlyaml
- name: Basic server setup
  hosts: webserver
  become: true

  tasks:
    - name: Update package list and install updates
      ansible.builtin.apt:
        update_cache: true
        cache_valid_time: 3600
        upgrade: safe

    - name: Install useful tools
      ansible.builtin.apt:
        name:
          - htop
          - curl
          - git
        state: present

    - name: Set time zone to Europe/Berlin
      community.general.timezone:
        name: Europe/Berlin

Line by line:

  • - name: at the top describes the play. A playbook can hold several plays; this one has one.
  • hosts: webserver sets which servers the play applies to.
  • become: true runs all tasks with sudo, like --become on the ad-hoc command.
  • tasks: is the list of jobs. Each has a name that Ansible shows while running, and exactly one module.
  • ansible.builtin.apt is the module’s full name. ansible.builtin are the modules that always ship with Ansible. community.general.timezone comes from a collection included in the ansible package.
  • cache_valid_time: 3600 only refreshes the package list if it’s older than an hour.

Now run the playbook:

Terminalbash
ansible-playbook basics.yml

PLAY [Basic server setup] ******************************************************

TASK [Gathering Facts] *********************************************************
ok: [web1]
ok: [web2]

TASK [Update package list and install updates] *********************************
changed: [web1]
changed: [web2]

TASK [Install useful tools] ****************************************************
ok: [web2]
changed: [web1]

TASK [Set time zone to Europe/Berlin] ******************************************
changed: [web2]
changed: [web1]

PLAY RECAP *********************************************************************
web1                       : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=4    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Gathering Facts is a task Ansible adds by itself. It collects information about the server that you can use as variables later. For the tools task, web2 only shows ok: on Ubuntu htop, curl and git were already installed, on Debian something was missing.

The final summary, the PLAY RECAP, is the part to read. changed counts the tasks that changed something, failed the errors. A second run right after ends with changed=0 on both servers. The state is already right, so Ansible leaves everything alone.

Step 5: Variables, templates and handlers

The second playbook sets up nginx with its own start page. It adds three new things: a variable, a template and a handler.

webserver.ymlyaml
- name: Set up web server with test page
  hosts: webserver
  become: true

  vars:
    page_title: "Hello from Ansible"

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

    - name: Set security header
      ansible.builtin.copy:
        dest: /etc/nginx/conf.d/security.conf
        content: "add_header X-Content-Type-Options nosniff always;\n"
        mode: "0644"
      notify: Reload Nginx

    - name: Create start page from template
      ansible.builtin.template:
        src: templates/index.html.j2
        dest: /var/www/html/index.html
        mode: "0644"

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

  handlers:
    - name: Reload Nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded
  • vars: defines the variable page_title. You use it in templates and tasks with double curly braces.
  • copy with content writes a file with fixed content. Here it’s one line of nginx configuration.
  • notify: Reload Nginx calls the handler with that name, but only if the task changed something. Handlers run at the end of the play, once, no matter how many tasks called them.
  • template takes a template, fills in variables and copies the result to the server.

The template lives in the templates subfolder. Ansible uses the Jinja2 language for it:

templates/index.html.j2html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{ page_title }}</title>
</head>
<body style="font-family: sans-serif; max-width: 40rem; margin: 4rem auto;">
  <h1>{{ page_title }}</h1>
  <p>Ansible created this page on <strong>{{ inventory_hostname }}</strong>.</p>
  <ul>
    <li>System: {{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }}</li>
    <li>IP address: {{ ansible_facts['default_ipv4']['address'] }}</li>
    <li>Memory: {{ ansible_facts['memtotal_mb'] }} MB</li>
  </ul>
</body>
</html>

inventory_hostname is the name from the inventory, so web1 or web2. The values under ansible_facts were collected by the Gathering Facts task. That way one template turns into a different page on each server.

Run the playbook with ansible-playbook webserver.yml. The first run installs nginx, writes both files and reloads nginx through the handler. The second run changes nothing, and since no task changed anything, the handler stays quiet too:

Two terminal outputs of ansible-playbook webserver.yml: the first run shows yellow changed lines and the handler “Reload Nginx”, the second run only green ok lines and changed=0

In the browser each server now shows its own start page:

Two browser windows with the page “Hello from Ansible”: web1 reports Debian 13.7, web2 reports Ubuntu 24.04, each with its own IP address and memory

curl shows whether the header arrives:

Terminalbash
curl -sI http://{{web1_ip}}/ | grep -i nosniff
X-Content-Type-Options: nosniff

Step 6: Check first, then change

Before a playbook rebuilds something on real servers, you want to know what will happen. That’s what --check (change nothing, just report) and --diff (show differences in files) are for. I changed the page title in the playbook to “Hello from the Ansible course” and then checked:

Terminalbash
ansible-playbook webserver.yml --check --diff
...
TASK [Create start page from template] *****************************************
--- before: /var/www/html/index.html
+++ after: /home/admin/.ansible/tmp/.../index.html.j2
@@ -2,10 +2,10 @@
 <html lang="en">
 <head>
   <meta charset="utf-8">
-  <title>Hello from Ansible</title>
+  <title>Hello from the Ansible course</title>
 </head>
 <body style="font-family: sans-serif; max-width: 40rem; margin: 4rem auto;">
-  <h1>Hello from Ansible</h1>
+  <h1>Hello from the Ansible course</h1>
   <p>Ansible created this page on <strong>web1</strong>.</p>

changed: [web1]
...
PLAY RECAP *********************************************************************
web1                       : ok=5    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=5    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The page on the servers stays as it was. Only a run without --check writes the new version.

To try a change on one server first, --limit restricts the run:

Terminalbash
ansible-playbook webserver.yml --limit web1

Step 7: Docker and an app with a playbook

Finally a playbook like the ones I actually use for my own servers: install Docker from the official repository and start an app with Docker Compose. The app is Uptime Kuma, a web interface that monitors websites and services.

Docker’s repository differs between Debian and Ubuntu. Instead of writing two playbooks, Ansible fills in the right values from the facts:

docker.ymlyaml
- name: Install Docker and start Uptime Kuma
  hosts: webserver
  become: true

  vars:
    distribution: "{{ ansible_facts['distribution'] | lower }}"

  tasks:
    - name: Set up Docker repository
      ansible.builtin.deb822_repository:
        name: docker
        types: deb
        uris: "https://download.docker.com/linux/{{ distribution }}"
        suites: "{{ ansible_facts['distribution_release'] }}"
        components: stable
        signed_by: "https://download.docker.com/linux/{{ distribution }}/gpg"

    - name: Install Docker
      ansible.builtin.apt:
        name:
          - docker-ce
          - docker-ce-cli
          - containerd.io
          - docker-buildx-plugin
          - docker-compose-plugin
        state: present
        update_cache: true

    - name: Create folder for Uptime Kuma
      ansible.builtin.file:
        path: /opt/uptime-kuma
        state: directory
        mode: "0755"

    - name: Copy compose.yaml
      ansible.builtin.copy:
        src: files/uptime-kuma.yaml
        dest: /opt/uptime-kuma/compose.yaml
        mode: "0644"

    - name: Start Uptime Kuma
      community.docker.docker_compose_v2:
        project_src: /opt/uptime-kuma
        state: present
  • | lower is a filter. It turns Debian into debian, the way it appears in the repository URL.
  • distribution_release is the system’s code name, trixie on Debian 13 and noble on Ubuntu 24.04.
  • deb822_repository creates the package source and downloads the signing key.
  • docker_compose_v2 starts the Compose project in the given folder, much like docker compose up -d.

The Compose file sits in the project’s files folder:

files/uptime-kuma.yamlyaml
services:
    uptime-kuma:
        image: louislam/uptime-kuma:2
        container_name: uptime-kuma
        restart: unless-stopped
        ports:
            - "127.0.0.1:3001:3001"
        volumes:
            - ./data:/app/data

The port is bound to 127.0.0.1 only. That keeps Uptime Kuma off the internet until you put a reverse proxy with HTTPS in front of it. The project now looks like this:

~/ansible-learn/Folders
  • ansible.cfg
  • inventory.iniyour servers
  • basics.yml
  • webserver.yml
  • docker.yml
  • templates/
  • index.html.j2
  • files/
  • uptime-kuma.yaml

After ansible-playbook docker.yml, Docker and Uptime Kuma run on both servers. A second run ends with changed=0 again. To open the interface, build an SSH tunnel from your machine to the server:

Terminalbash
ssh -L 3001:127.0.0.1:3001 {{server_user}}@{{web1_ip}}

While that connection is open, Uptime Kuma is at http://localhost:3001. On the first visit the app asks which database to use; SQLite is enough to start:

Uptime Kuma 2.5 setup page at localhost:3001 with the language set to English and the database question: Embedded MariaDB, MariaDB/MySQL or SQLite

Common errors

UNREACHABLE!: Ansible can’t reach the server over SSH. Check IP address, user name and key with a plain ssh {{server_user}}@{{web1_ip}}. What fails there fails with Ansible too.

Missing sudo password: Your user needs a password for sudo. Run the command with -K.

Host key question on the first run: Ansible is waiting for you to confirm the fingerprint. Log in once over SSH beforehand, as described under prerequisites.

Handlers after an error: If a run aborts, Ansible doesn’t remember which handlers were still pending. That happened to me during testing. The handler that reloads nginx failed because Debian 13 already sets an option in nginx.conf that my file tried to set again. After the fix, the next run reported changed=0 and didn’t reload nginx. In that case, reload the service once by hand:

Terminalbash
ansible webserver -m ansible.builtin.service -a "name=nginx state=reloaded" --become

Where to go next

With these three playbooks you know the essentials. When the files grow, these tools help:

  • Roles bundle tasks, templates, files and handlers into one package, such as a docker role you reuse in several playbooks. ansible-galaxy role init docker creates the folder structure.
  • Ansible Galaxy is a collection of ready-made roles and collections from other users.
  • ansible-vault encrypts passwords and API keys so they don’t sit in the project as plain text.
  • Git belongs in every Ansible project. It shows who changed what on your servers and when. The Git tutorial shows how.

Frequently asked questions

Frequently asked questions

Do I have to install anything on the servers?

No. Ansible only needs SSH and Python on the servers. Debian and Ubuntu ship both.

Does Ansible run on Windows?

Not directly. On Windows you install WSL with Ubuntu and use the same commands as on a Linux machine.

What is the difference between ansible and ansible-playbook?

ansible runs a single task as an ad-hoc command. ansible-playbook runs a whole playbook with many tasks.

Why use Ansible instead of a shell script?

A shell script runs commands no matter what state the server is in. Ansible checks the state first and only changes what is missing. That makes it safe to run a playbook several times, and the recap shows what changed.

Can I manage my home server with Ansible?

Yes. Any machine with SSH and Python works as a managed node, including a Raspberry Pi or a mini PC at home.