Skip to content

Instantly share code, notes, and snippets.

@XavM
Last active September 2, 2016 09:49
Show Gist options
  • Save XavM/3ba4b3e55ebe3f4758c1 to your computer and use it in GitHub Desktop.
Save XavM/3ba4b3e55ebe3f4758c1 to your computer and use it in GitHub Desktop.
Create an openVZ template (tar ball) from a running CT
#!/bin/bash
## Create an openVZ template (tar ball) from a running CT
set -eo pipefail
if [ -z $1 ]
then
echo "Usage: vztmpl-cr CTID [NAME]"
exit 1
fi
main() {
local CTID="$1"
local OSTEMPLATE="$(vzlist -Ho ostemplate ${CTID})"
local DEFAULT_NAME="${OSTEMPLATE}_${CTID}_$(date +%F)"
local NAME="/tmp/${2:-$DEFAULT_NAME}"
# Known snapshot ID
local ID=$(uuidgen)
# Directory used to mount the snapshot
local MNTDIR="$(mktemp -d)"
# Take a snapshot without suspending a CT and saving its config
vzctl --quiet snapshot $CTID --id $ID --skip-suspend --skip-config \
|| exit 3
# Mount the snapshot taken
vzctl --quiet snapshot-mount $CTID --id $ID --target $MNTDIR \
|| exit 3
# Create the template tar ball from the mounted snapshot
GZIP=-9 tar zcf "${NAME}.tar.gz" -C $MNTDIR --warning=none . \
|| exit 3
# Unmount the snapshot
vzctl --quiet snapshot-umount $CTID --id $ID \
|| exit 3
# Delete (merge) the snapshot
vzctl --quiet snapshot-delete $CTID --id $ID \
|| exit 3
# Delete MNTDIR
rm -rf $MNTDIR
# Output template path
echo "${NAME}.tar.gz"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment