Automating package maintenance with Ansible
The first of many lazy automations
Hey there fellow sysadmins! 👋 I’ve been playing with Ansible to keep my Linux servers tidy and up-to-date. I thought that an interesting idea to start with could be to keep the package managers clean and up to date using Ansible.
What are we building? 👷🏼
The main objective will be to create tasks in Ansible to handle the main operating system package manager, regardless of which one it is.
Let’s dive into the code!
Ansible tasks 🧑🏻💻
We want to keep the package manager clean and the packages updated to the latest version available. Luckily, Ansible has several pre-built modules for this, such as apk, apt and dnf (cool, right?).
In addition, Ansible has a magic variable called ansible_pkg_mgr that indicates which is the main package manager inside the system, so we can execute the specific tasks for each system.
This would be the final result:
1- name: "Update and clean APK"
2 when: "ansible_pkg_mgr == 'apk'"
3 ansible.builtin.apk:
4 available: true
5 update_cache: true
6 upgrade: true
7
8- name: "Update and clean APT"
9 when: "ansible_pkg_mgr == 'apt'"
10 ansible.builtin.apt:
11 autoclean: true
12 autoremove: true
13 cache_valid_time: 3600
14 purge: true
15 update_cache: true
16 upgrade: true
17
18- name: "Update and clean DNF"
19 when: "ansible_pkg_mgr == 'dnf'"
20 block:
21 - name: "Update DNF packages"
22 ansible.builtin.dnf:
23 name: "*"
24 state: "latest"
25 update_cache: true
26 update_only: true
27
28 - name: "Autoremove DNF packages"
29 ansible.builtin.dnf:
30 autoremove: true
Important details 🧑🏻🏫
Here are some awesome things about this tasks:
- They’re idempotent (safe to run multiple times).
- Works across different Linux distributions.
But there are a few “not so cool” things too:
- Not 100% tested.
- They may not work on all Linux distributions.
- They don’t handle all the possible package managers.
- Surely there’s a better way to do this!