Automating Ubuntu 16 Updates With Vultr Startup Scripts

Published on: Fri, Mar 3, 2017 at 3:32 pm EST
FAQ Ubuntu

Ubuntu 16 and newer performs periodic tasks related to apt (such as updating the package list, and applying unattended upgrades) using a systemd timer. This timer is usually triggered at the start of launching an Ubuntu 16 VPS, which can cause apt tools (apt, apt-get) to fail with an error similar to the following:

E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)

A common use case of Vultr startup scripts is to update the system packages. Without checking the error codes returned from apt or apt-get, system updates can fail. When the lock condition is encountered, apt will typically return code 100.

This sample script can be used as a Vultr startup script to retry installing system updates. You can modify it to fit your needs.

#!/bin/bash
UPGRADE_ATTEMPT_COUNT=100
UPGRADE_STATE=1
for i in `seq 1 $UPGRADE_ATTEMPT_COUNT`;
do
    if [ "$UPGRADE_STATE" -eq "1" ]; then
        apt-get -y update
        if [ "`echo $?`" -eq "0" ]; then
            echo "package list updated."
            UPGRADE_STATE=2;
        fi
    fi

    if [ "$UPGRADE_STATE" -eq "2" ]; then
        apt-get -y upgrade
        if [ "`echo $?`" -eq "0" ]; then
            echo "packages updated."
            UPGRADE_STATE=3;
        fi
    fi

    if [ "$UPGRADE_STATE" -eq "3" ]; then
        break
    fi

    sleep 5
done

if [ "$UPGRADE_STATE" -ne "3" ]; then
    echo "ERROR: packages failed to update after $UPGRADE_ATTEMPT_COUNT attempts."
fi

More information about Automatic Updates is available in the Ubuntu LTS documentation.

Want to contribute ?

You could earn up to $300 by adding new articles