Published:

Jarle Aase

Ansible Playbook to dist-upgrade Debian

bookmark 1 min read

I know it's not considered best practice to do unattended dist upgrades for servers. However, I have a handful of servers and VM's that have very few packages installed. The bare metal servers run VM's using kvm. The VM's run docker and ssh, and most of them are just build nodes for Jenkins.

I failed to find a playbook for this. So here it is. The playbook upgrades from Debian Bullseye to Debian Bookworm

Note that the script assumes that the machines are already up to date with the latest updates for the installed version of Debian. I have another script to handle that.

dist-upgrade.yaml

---
- hosts: bld-worker2
  become: true
  remote_user: jgaa
  become_user: root
  vars_prompt:
    - name: "ansible_become_pass"
      prompt: "Su password"
      private: yes
  tasks:
    - name: Prepare. Autoremove old packages
      apt:
        autoremove: true
        clean: true

    - name: Upgrade to latest release (apt-get dist-upgrade)
      ansible.builtin.shell: |
        sed -i 's/bullseye/bookworm/g' /etc/apt/sources.list
        sed -i 's/non-free non-free-firmware-firmware//g' /etc/apt/sources.list
        if ! grep non-free-firmware /etc/apt/sources.list
        then
            sed -i 's/non-free/non-free non-free-firmware/g' /etc/apt/sources.list
        fi

    - name: Update apt repo and cache on all Debian/Ubuntu boxes
      apt:
        update_cache: yes
        force_apt_get: yes
        cache_valid_time: 0

    - name: Upgrade all packages on servers
      apt: upgrade=dist force_apt_get=yes

    - name: Check if a reboot is needed on all servers
      register: reboot_required_file
      stat: path=/var/run/reboot-required get_md5=no

    - name: Reboot the box if kernel updated
      reboot:
        msg: "Reboot initiated by Ansible for kernel updates"
        connect_timeout: 5
        reboot_timeout: 300
        pre_reboot_delay: 0
        post_reboot_delay: 30
        test_command: uptime
      when: reboot_required_file.stat.exists

I don't allow root access via ssh, so ansible connects as me, and then su to root.