Linux

Automating Ubuntu Software Installation with Ansible: Playbooks for Server Provisioning

Aseem Kishore
13 min read

The Back Room Tech is reader-supported. We may earn a commission when you buy through links on our site. Learn more.

This guide automates Ubuntu software installation with Ansible. You start with one control node and finish with a reusable role that installs packages on a group of Ubuntu LTS servers. Along the way it covers the decisions that matter in production: present vs latest, how to supply the sudo password, when handlers fire, and why you dry-run before every real change.

The short answer to the most common question: Ansible goes on one machine only. That machine is the control node. The servers you manage need SSH access and a Python interpreter, and nothing else. No agent, no Ansible install on the targets.

What Is Ansible?

Ansible is an open-source automation engine. You describe the desired state of a server in YAML playbooks: which packages are installed, which files exist, and which services run. Ansible connects over SSH and applies that state to one host or hundreds.

The core idea is idempotency. A task reports changed only when it actually alters the system. For well-written, idempotent tasks, running the same playbook twice should produce little or no changed output on the second run — though factors like external changes to package state, handlers, or environment drift can still cause a changed result. That’s what makes idempotent playbooks safe to rerun. A pile of apt-get shell scripts can’t promise the same.

Prerequisites

  • A Linux control node with sudo access. This guide uses Ubuntu. A spare VM, a mini PC, or a Raspberry Pi in the homelab all work.
  • One or more managed servers running a supported Ubuntu LTS release: Ubuntu 26.04 LTS “Resolute Raccoon” (supported to May 2031) or Ubuntu 24.04 LTS “Noble Numbat” (supported until 2029). See the Ubuntu release cycle.
  • SSH key authentication from the control node to each managed server.
  • A user on each managed server with sudo rights.
  • python3 on each managed server. Confirm it’s present by running python3 --version on a target; if it’s missing, install it before continuing.
RequirementDetails
Control nodeUbuntu with ansible-core installed
Managed nodesUbuntu 26.04 LTS or 24.04 LTS, SSH + Python only
NetworkSSH (port 22 by default) reachable from the control node
Privilegessudo on managed nodes, used through become

Tip: If your servers live on a single homelab switch with no battery backup, add a UPS before you automate upgrades. A power cut halfway through apt is a bad time to discover you need one.

Step-by-Step Guide

Step 1: Install ansible-core on the Control Node

Run this on the control node only:

sudo apt update
sudo apt install -y ansible-core   # -y answers "yes" to the install prompt

ansible-core ships the engine and its built-in modules, which you reference under the ansible.builtin namespace. It doesn’t include the community collections. Every module used here is built in, so you don’t need the larger ansible community package.

Alternative: the Ansible PPA. The official install guide also documents a PPA for newer releases:

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

Warning: The PPA doesn’t always publish builds for a brand-new Ubuntu LTS at launch. On 26.04, check that the PPA lists your codename before you depend on it. If it doesn’t, stick with the distro ansible-core package.

Verify the install:

ansible --version

Expected result: The first line shows the installed ansible [core x.y.z] version. Below it you’ll see the active config file, the module search paths, and the Python version Ansible runs under. Note the version you got and check the Ansible docs for that release. I’m not pinning a version number here on purpose.

Output of `ansible --version` on the Ubuntu control node, showing the ansible core version line, config file path, and python version line

Step 2: Create the Project Layout and ansible.cfg

Keep everything in one directory so it can live in Git:

mkdir -p ~/ansible-provision/group_vars/ubuntu_servers
cd ~/ansible-provision

Create a local config file:

# ~/ansible-provision/ansible.cfg
[defaults]
inventory = inventory.ini
# Prompt to accept new host keys rather than disabling checking
host_key_checking = True

Ansible reads ansible.cfg from the current working directory. That means you can drop -i inventory.ini from every command, as long as you run it from ~/ansible-provision. Rerun ansible --version here. The config file line should now point at this file.

Step 3: Build an Inventory with Host Groups

# ~/ansible-provision/inventory.ini
[web_servers]
web01 ansible_host=192.0.2.11
web02 ansible_host=192.0.2.12

[db_servers]
db01 ansible_host=192.0.2.21

# Parent group containing both groups above
[ubuntu_servers:children]
web_servers
db_servers

[ubuntu_servers:vars]
ansible_user=deploy

Replace the 192.0.2.x addresses with your servers’ real IPs. That range is reserved for documentation. Replace deploy with the sudo-capable user you SSH in as.

Show the file:

cat inventory.ini
Output of `cat inventory.ini` showing the [web_servers], [db_servers], and [ubuntu_servers:children] group headers with host entries

Now confirm that the inventory parses and that every host answers:

ansible-inventory --graph              # prints the group/host tree
ansible ubuntu_servers -m ansible.builtin.ping

Expected result: Each host returns SUCCESS with “ping”: “pong”. The ping module runs over SSH and executes Python on the target, so you’re testing both at once. It also proves that managed hosts need nothing beyond SSH and Python.

Step 4: Define Group Variables

The group variables file holds the package list, so the playbook stays generic:

# ~/ansible-provision/group_vars/ubuntu_servers/main.yml
baseline_packages:
  - curl
  - htop
  - unattended-upgrades
  - nginx

Any file under group_vars/<group_name>/ applies to every host in that group. Later you can add group_vars/db_servers/main.yml to give database hosts a different list.

Step 5: Write the Playbook

# ~/ansible-provision/site.yml
---
- name: Provision Ubuntu servers
  hosts: ubuntu_servers
  become: true   # escalate with sudo for every task in this play

  tasks:
    - name: Install baseline packages
      ansible.builtin.apt:
        name: "{{ baseline_packages }}"
        state: present
        update_cache: true
        cache_valid_time: 3600   # skip apt update if the cache is under 1 hour old
      tags: [packages]

    - name: Hide nginx version in response headers
      ansible.builtin.copy:
        dest: /etc/nginx/conf.d/server-tokens.conf
        content: "server_tokens off;\n"
        owner: root
        group: root
        mode: "0644"
      notify: Restart nginx
      tags: [config]

  handlers:
    - name: Restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Three decisions in this file matter more than the syntax.

state: present vs state: latest. present installs a package if it’s missing and leaves an installed version alone. latest upgrades to whatever version the repo offers at runtime. On a production server, that means an untested upgrade can land during a routine run. Use present for provisioning. Keep upgrades in a separate, deliberate playbook that you test on staging first.

update_cache with cache_valid_time. Stale apt metadata on a fresh server can cause failed installs, so refresh the cache. cache_valid_time stops Ansible from running apt update on every single run.

The handler. notify: Restart nginx only fires when the copy task reports changed. On a rerun the file already matches, so nginx doesn’t restart. That’s why you use a handler instead of a plain “restart nginx” task. The play stays idempotent and doesn’t bounce services for no reason.

One production caveat: a restart with a broken config file leaves nginx stopped. Before you reuse this pattern for real nginx configuration, add a validation step, such as a handler that runs nginx -t ahead of the restart, so a bad file fails the play instead of taking the service down.

Prefer ansible.builtin.apt over ansible.builtin.package for Ubuntu-only playbooks. The generic package module hands work to the OS package manager. But it doesn’t carry apt-specific options like cache_valid_time.

Step 6: Lint the Playbook

ansible-lint is a linter for Ansible content. It’s designed to flag common style and correctness issues before they reach a server. Ubuntu ships it in the universe component of the Ubuntu repositories, so universe must be enabled. Versions differ a lot by release: Launchpad lists 6.17.2 for 24.04 and 26.1.1 for 26.04. If the packaged release is too old for your playbooks, follow the method in the official ansible-lint docs, which also document the current set of rules it checks:

sudo apt install -y ansible-lint
ansible-lint site.yml

Expected result: A clean pass, or a list of rule violations with file and line numbers. Fix each one and rerun until it’s clean. Rule names and output format vary by ansible-lint version.

Step 7: Dry-Run with –check –diff

ansible-playbook site.yml --check --diff --ask-become-pass
# --check: report what would change, change nothing
# --diff: show file content differences
# --ask-become-pass (-K): prompt once for the sudo password

Expected result: On servers that already have nginx installed, tasks that would act show as changed in yellow, and the copy task prints a diff that adds server_tokens off;. On a brand-new host the output can differ; see the note below. The PLAY RECAP at the end sums up ok, changed, and failed per host. Nothing on the servers has changed yet.

Output of `ansible-playbook site.yml --check --diff --ask-become-pass` showing a diff block for /etc/nginx/conf.d/server-tokens.conf and the PLAY RECAP summary

Note: Check mode can’t install packages. On a brand-new host, a later task can fail because it depends on something not yet installed. Here, the copy task may fail because /etc/nginx/conf.d doesn’t exist until the package is installed, and the nginx handler may fail because the nginx service doesn’t exist yet. That’s a known limit of dry runs on first provisioning. The playbook itself is fine.

Step 8: Run It for Real, Then Run It Again

ansible-playbook site.yml --ask-become-pass

Expected result: The first run shows changed for the package and config tasks. The Restart nginx handler runs at the end of the play. PLAY RECAP shows failed=0 for every host.

ansible-playbook run showing ok and changed task states, the RUNNING HANDLER [Restart nginx] line, and PLAY RECAP totals

Now run the exact same command again. This second run is a useful idempotency check. For idempotent tasks like these, you should typically see ok across the board, changed=0 in the recap, and no handler run — though package state changes made outside Ansible, or environment drift, can still cause a task to report changed. If a task shows changed on every rerun with no external changes involved, treat that as a sign the task isn’t idempotent. See the troubleshooting section below.

To run just one part of the playbook, use tags:

ansible-playbook site.yml --tags config --ask-become-pass

Step 9: Convert the Playbook into a Role

A flat playbook works for one project. A role lets you reuse the same logic across dev, staging, and prod. Build it by hand so you know what each file does:

mkdir -p roles/baseline/{tasks,handlers,defaults}
# ~/ansible-provision/roles/baseline/defaults/main.yml
baseline_packages:
  - curl
  - htop
# ~/ansible-provision/roles/baseline/tasks/main.yml
---
- name: Install baseline packages
  ansible.builtin.apt:
    name: "{{ baseline_packages }}"
    state: present
    update_cache: true
    cache_valid_time: 3600
  tags: [packages]

- name: Hide nginx version in response headers
  ansible.builtin.copy:
    dest: /etc/nginx/conf.d/server-tokens.conf
    content: "server_tokens off;\n"
    owner: root
    group: root
    mode: "0644"
  notify: Restart nginx
  tags: [config]
# ~/ansible-provision/roles/baseline/handlers/main.yml
---
- name: Restart nginx
  ansible.builtin.service:
    name: nginx
    state: restarted

Now replace site.yml with a short wrapper that calls the role:

# ~/ansible-provision/site.yml
---
- name: Provision Ubuntu servers
  hosts: ubuntu_servers
  become: true
  roles:
    - baseline

defaults/main.yml holds the lowest-priority values. Your group_vars entries override them. Each environment’s inventory can supply its own package list, and nobody has to touch the role.

find roles/baseline -type f
Output of `find roles/baseline -type f` showing tasks/main.yml, handlers/main.yml, and defaults/main.yml

The finished project looks like this:

~/ansible-provision/
├── ansible.cfg
├── inventory.ini
├── group_vars/
│ └── ubuntu_servers/
│ └── main.yml
├── roles/
│ └── baseline/
│ ├── defaults/main.yml
│ ├── handlers/main.yml
│ └── tasks/main.yml
└── site.yml

Rerun ansible-lint site.yml and --check --diff. Against already-provisioned servers, the role should report no changes. That confirms the refactor didn’t alter behavior.

Configuration

Supplying the sudo Password Safely

Never put ansible_become_password: hunter2 in plaintext. Use one of these instead:

MethodHowBest for
Prompt--ask-become-pass / -KInteractive runs
Vault-encrypted varansible_become_password in an encrypted fileUnattended runs, CI
Passwordless sudo for the deploy usersudoers rule on targetsDedicated automation accounts (weigh the risk)

For the Vault route:

ansible-vault create group_vars/ubuntu_servers/vault.yml

Inside the editor that opens, add:

ansible_become_password: YOUR_SUDO_PASSWORD

Then run with --ask-vault-pass instead of -K. One catch: this applies one password to every host in the group. Check the official privilege escalation docs for current options before you standardize on a method.

Key Settings Reference

SettingDefaultNotes
becomefalseSet at play or task level
state (apt)presentlatest = unplanned upgrades
update_cache (apt)falseEnable on provisioning tasks
cache_valid_time (apt)unsetSeconds; avoids repeat apt update
inventory (ansible.cfg)noneOr pass -i

Tips and Troubleshooting

Service didn’t restart after a config change

Why it happens: Handlers fire only when the notifying task reports changed, and only at the end of the play. If the file already matched, nothing fires. If a later task failed, the play stopped before handlers ran.

Fix: Check the task status in the run output. If a failure blocked the handler, fix it and rerun. The --force-handlers flag runs notified handlers even after a failure. Also confirm that the notify: string exactly matches the handler name:.

Task reports changed on every run

Why it happens: Package installs done through ansible.builtin.shell or ansible.builtin.command don’t check current state. They always report a change.

Fix: Replace them with ansible.builtin.apt. That module checks the current package state before it acts.

Permission denied or “Missing sudo password”

Why it happens: The task needs root, but become: true isn’t set, or no become password was supplied.

Fix: Add become: true to the play or task, and run with -K or a vault-encrypted variable.

apt install ansible fails from the PPA on a new Ubuntu release

Why it happens: The PPA may not have published builds for your release’s codename yet. Check the PPA’s Launchpad page for your codename (lsb_release -cs) rather than assuming either way.

Fix: Remove the PPA and run sudo apt install ansible-core from the Ubuntu repositories.

Installs fail with “No package matching” or stale metadata

Why it happens: The apt cache on the target is out of date.

Fix: Set update_cache: true on the apt task. If you add third-party repos, run lsb_release -cs on the target and use that codename. Don’t copy jammy from an example.

Wrapping Up

You now have a role you can lint, dry-run with --check --diff, and apply idempotently to the Ubuntu 24.04 or 26.04 LTS hosts in your inventory. Run those checks against your own servers before you trust it in production. Adding a server is one line in inventory.ini.

My take: the role structure is nice to have, but the --check --diff habit and the second-run idempotency check are what keep production safe. Next, split upgrades into their own playbook that uses state: latest, and move your inventory and roles into Git.

StepActionApplies To
1–2Install ansible-core, create ansible.cfgControl node
3–4Inventory + group_varsControl node
5–8Playbook, lint, dry run, real runManaged nodes
9Refactor into a roleReuse across environments

Sources