Task

Automate System Updates safely and cleanly

Ansible · 10 min · Practical

A streamlined playbook to keep your Debian/Ubuntu hosts patched. It updates the apt cache, performs a distribution upgrade, and automatically prunes orphaned dependencies.

Why this playbook holds up

Routine maintenance shouldn't require logging into every server manually. By leveraging Ansible's native `apt` module, you ensure uniform patch levels across your entire fleet while keeping the disk clear of stale packages.

Smart Dependency Handling

Using dist upgrade intelligently handles changing dependencies with new versions of packages, preventing held packages and broken states.

Built-in Autoremove

Automatically cleans up libraries and dependencies that were installed with previous software but are no longer needed, freeing up disk space.

The full task list

update.yml
---
- name: System update and cleanup
  hosts: localhost
  become: yes
  tasks:
    - name: Update apt cache and upgrade all packages
      apt:
        upgrade: dist
        update_cache: yes

    - name: Remove unused dependencies
      apt:
        autoremove: yes

Run order

  • sync & patch Refreshes the local repository cache and upgrades all installed packages to their latest versions.

    apt, update_cache + dist

  • sweep Identifies and removes orphaned dependencies left behind by the upgraded packages.

    apt, autoremove

Confirm the host is clean

To verify the playbook did its job, you can run a dry-run check on the host to ensure no pending upgrades or leftover packages remain.

terminal

$ apt list --upgradable
Listing... Done

$ apt autoremove --dry-run
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

$

Lessons from running this in production