Shell script to update all lxd container hypervisor

in Categories Automation & Management, Virtualization last updated September 5, 2016

A simple shell script wrapper to update all lxd container hypervisor images eitehr running Debian or Ubuntu Linux.

#!/bin/bash
# A simple shell script to update all lxd container hypervisor
# URL: https://bash.cyberciti.biz/virtualization/shell-script-to-update-all-lxd-container-hypervisor/
# Tested on : Ubuntu 16.04 LTS lxd server 
# Tested on : Ubuntu/Debian lxd container hypervisor only 
# ----------------------------------------------------------------------------
# Author: nixCraft 
# Copyright: 2016 nixCraft under GNU GPL v2.0+
# ----------------------------------------------------------------------------
# Last updated 14 Aug 2016
# ----------------------------------------------------------------------------
# Set full path to bins 
_apt="/usr/bin/apt-get"
_lxc="/usr/bin/lxc"
_awk="/usr/bin/awk"
 
# Get containers list
clist="$(${_lxc} list -c ns | ${_awk} '!/NAME/{ if ( $4 == "RUNNING" ) print $2}')"
 
# Use bash for loop and update all container hypervisor powered by Debian or Ubuntu
# NOTE: for CentOS use yum command instead of apt-get
for c in $clist
do
	echo "Updating Debian/Ubuntu container hypervisor \"$c\"..."
	${_lxc} exec $c ${_apt} -- -qq update
	${_lxc} exec $c ${_apt} -- -qq -y upgrade
	${_lxc} exec $c ${_apt} -- -qq -y clean
	${_lxc} exec $c ${_apt} -- -qq -y autoclean
done

Run script as follows:
$ /path/to/update.lxd.vms
Sample outputs:

Updating Debian/Ubuntu container hypervisor "wwwapp1"...
Updating Debian/Ubuntu container hypervisor "msyqldb1"...
Updating Debian/Ubuntu container hypervisor "memcache1"...
Updating Debian/Ubuntu container hypervisor "nginx1"...
Updating Debian/Ubuntu container hypervisor "apachephp1"...

Share this on:

5 comment

  1. Better and automated approach would be to install and configure unattended-upgrades on the containers

  2. Thank you for publishing this, very helpful. For those of us learning bash scripts, could you break down this line? I think I understand what it does, but having the explanation would be great.
    Thanks
    clist="$(${_lxc} list -c ns | ${_awk} '!/NAME/{ if ( $4 == "RUNNING" ) print $2}')"

    1. 1. Find list of running container lxc with list -c ns
      2. Use awk to print a list of container which are running but exclude header NAME with awk command

    Have a question? Post it on our forum!