Upgrading packages with Ansible
By Érico Andrei

Upgrading packages with Ansible

Earlier today, I was tasked with updating system packages on a series of Debian-like servers for one of our clients. Given that we utilize Ansible to manage their servers, I initially thought this would be straightforward.

        - name: "Packages: Upgrade"
          ansible.builtin.apt:
            upgrade: safe
            update_cache: true
            only_upgrade: true
            cache_valid_time: 86400  # One day

However, there was a specific requirement: Docker should not be upgraded. To ensure Docker packages remained untouched, I employed the ansible.builtin.dpkg_selections module.

        - name: "Docker: Prevent packages from being upgraded"
          ansible.builtin.dpkg_selections:
            name:
              - docker-ce
              - docker-ce-cli
              - containerd.io
              - docker-compose
            selection: hold

Upon executing the playbook on a test server, I noticed an unexpected outcome: Docker packages had been upgraded, and the dpkg hold was no longer in place.

sudo apt-mark showhold

This anomaly arises because aptitude disregards the holds established by ansible.builtin.dpkg_selections. To circumvent this, it's essential to use the force_apt_get option with the ansible.builtin.apt module.

        - name: "Docker: Prevent packages from being upgraded"
          ansible.builtin.dpkg_selections:
            name:
              - docker-ce
              - docker-ce-cli
              - containerd.io
              - docker-compose
            selection: hold

        - name: "Packages: Upgrade"
          ansible.builtin.apt:
            upgrade: safe
            update_cache: true
            only_upgrade: true
            cache_valid_time: 86400  # One day
            force_apt_get: true  # Needed to avoid upgrading also held packages