LXC 3 – the missing utilities

I have been using LXC for a while and there are a few commands i would like to have in my toolbox. In this article i will provide you with a few scripts for managing your LXC containers.

lxc-rsync

Command to copy an entire container to another server.

#!/bin/bash

LXCPATH="/var/lib/lxc"

die() { echo -e "$*" && exit 1; }

run() {
	$* &> /dev/null
	if [[ $? -eq 0 ]]
	then echo -n "[OK]   "
	else echo -n "[FAIL] "
	fi
	echo "$*"
}

[[ $# -lt 2 ]] && \
	die "[error] Missing args!\nSyntax: $0 container lxchost2"

[[ -f "${LXCPATH}/${1}" ]] && \
	die "[error] Container not found in path '${LXCPATH}/${1}"

run ssh $2 lxc-stop -n $1
run lxc-stop -n $1
run rsync --numeric-ids -azh --delete ${LXCPATH}/${1} ${2}:${LXCPATH}/
run lxc-start -n $1

lxc-tar

Tar and gzip a container

#!/bin/bash

cd /var/lib/lxc

case $1 in
"pack")
	# Check if container exists
	[[ ! -f ${2}/config ]] && echo "container not found!" && exit 1

	# Check if previous archive exists
	[[ -f ${2}.tgz ]] && echo "Archive already exists, rename or remove it!" && exit 1

	# Warn if container is an overlay snapshot
	if grep overlay ${2}/config
	then read -p "Config contains the keyword overlayfs! CTRL+C to quit..." DUMMY
	fi

	# Stop if running and save last state
	STATE="$(lxc-info --state -n $2)"
	if [[ $STATE =~ RUNNING ]] ; then
		echo "Stopping $2 before backup..."
		LAST_STATE="RUNNING"
		lxc-stop -n $2 
	fi

	# Tar backup
	tar --numeric-owner -czf ${2}.tgz $2
	if [[ $? -eq 0 ]] ; then
		echo -n "Successfully created archive: "
		du -hs ${2}.tgz
	else
		echo "Failed to create archive!"
	fi

	# Restart if container was previously running
	if [[ $LAST_STATE -eq "RUNNING" ]] ; then
		echo "Starting up $2 again..."
		lxc-start -n $2
	fi

	;;

"unpack")
	# Check if container exists
	[[ -f ${2}/config ]] && echo "Container already exist!" && exit 1

	# Else unpack tar archive
	tar --numeric-owner -xzf ${2}
	;;

*)
	echo "Syntax:"
	echo "$0 pack container-name"
	echo "$0 unpack backup.tgz"
	;;
esac

lxc-restart

 #!/bin/bash
lxc-stop -n $1 && lxc-start -n $1
Categorized as LXC3