Skip to main content

Container Update Script

I've got the following script to run on a schedule to update my containers. Following this will schedule a weekly update at 0300 on Sunday.

In the shell, do:

nano /opt/autoupdate.sh

and enter this:

#!/bin/bash
# update all containers

# list of container ids we need to iterate through
containers=$(/usr/sbin/pct list | tail -n +2 | cut -f1 -d' ')

function update_container() {
  container=$1
  echo "[Info] Updating $container"
  # to chain commands within one exec we will need to wrap them in bash
  /usr/sbin/pct exec $container -- bash -c "apt update && apt upgrade -y && apt autoremove -y"
}

for container in $containers
do
  status=`/usr/sbin/pct status $container`
  if [ "$status" == "status: stopped" ]; then
    echo [Info] Starting $container
    /usr/sbin/pct start $container
    echo [Info] Sleeping 5 seconds
    sleep 5
    update_container $container
    echo [Info] Shutting down $container
    /usr/sbin/pct shutdown $container &
  elif [ "$status" == "status: running" ]; then
    update_container $container
  fi
done; wait

This will start any stopped containers, update them, then shut them back down. Any containers running when this is executed will stay running

To schedule this, I used crontab:

crontab -e

Add this line:

0 3 * * 0 /bin/bash /opt/autoupdate.sh

You may need to update permissions for the script:

chmod +x /opt/autoupdate.sh