Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 121 lines (94 sloc) 2.53 KB
#!/bin/bash
set -e
function log {
echo "$(date '+%Y-%m-%d %H:%M:%S') | $1"
}
function do_import {
ARGNUM=2
if [ $# -lt $ARGNUM ] || [ $# -gt $ARGNUM ]; then
echo 1>&2 "$0 import {imagePath} {containerName}"
exit 2
fi
IMPORTPATH=$1
CONTAINER=$2
HASH=$(echo $CONTAINER | shasum | cut -b 1-40)
IMAGE="$HASH-import"
log "importing template $IMPORTPATH as container $CONTAINER"
log "importing image file"
lxc image delete $IMAGE 2>/dev/null || true
lxc image import $IMPORTPATH --alias=$IMAGE >/dev/null 2>&1
log "creating container"
lxc init $IMAGE $CONTAINER >/dev/null || true
log "cleaning up"
lxc image delete $IMAGE 2> /dev/null
log "done."
}
function do_export {
ARGNUM=2
if [ $# -lt $ARGNUM ] || [ $# -gt $ARGNUM ]; then
echo 1>&2 "$0 export {containerName} {exportPath without .tar.gz}"
exit 2
fi
if lxc info $1 2>/dev/null | egrep -iqc "status: running"; then
ISRUNNING=true
else
ISRUNNING=false
fi
CONTAINER=$1
EXPORTPATH=$2
HASH=$(echo $CONTAINER | shasum | cut -b 1-40)
IMAGE="$HASH-export"
SNAPSHOT="$HASH-export"
touch $EXPORTPATH.tmp
rm $EXPORTPATH.tmp
log "exporting container $CONTAINER to $EXPORTPATH.tar.gz"
log "preparing snapshot"
lxc delete $CONTAINER/$SNAPSHOT 2>/dev/null || true
lxc image delete $IMAGE 2>/dev/null || true
if [ "$ISRUNNING" = true ] ; then
log "stopping container"
lxc stop $CONTAINER 2>/dev/null
fi
log "creating snapshot"
lxc snapshot $CONTAINER $SNAPSHOT >/dev/null
if [ "$ISRUNNING" = true ] ; then
log "starting container"
lxc start $CONTAINER
fi
log "creating image"
lxc publish $CONTAINER/$SNAPSHOT --alias=$IMAGE description="Exported from $CONTAINER at $(date '+%Y-%m-%d %H:%M')" >/dev/null
log "exporting image"
lxc image export $IMAGE $EXPORTPATH >/dev/null
log "cleaning up"
lxc delete $CONTAINER/$SNAPSHOT
lxc image delete $IMAGE
log "done."
}
function do_clean {
ARGNUM=1
if [ $# -lt $ARGNUM ] || [ $# -gt $ARGNUM ]; then
echo 1>&2 "$0 clean {containerName}"
exit 2
fi
CONTAINER=$1
EXPORTPATH=$2
HASH=$(echo $CONTAINER | shasum | cut -b 1-40)
IMAGE="$HASH-export"
log "Removing auto-created snapshot $IMAGE from container $CONTAINER"
lxc delete $CONTAINER/$IMAGE || true
log "done."
}
case $1 in
"clean")
do_clean $2
;;
"export")
do_export $2 $3
;;
"import")
do_import $2 $3
;;
*)
echo "Wrong Parameters! Usage: [ export | import | clean | help ]"
;;
esac
You can’t perform that action at this time.