Skip to content

Instantly share code, notes, and snippets.

@mbuiro
Last active March 22, 2020 17:45
Show Gist options
  • Save mbuiro/3b1d79d75ab17c0e7cb24cff6767b636 to your computer and use it in GitHub Desktop.
Save mbuiro/3b1d79d75ab17c0e7cb24cff6767b636 to your computer and use it in GitHub Desktop.
Very basic script to backup lxd containers to tar file
#!/bin/bash
DATE=`date +%m-%d-%Y`
OLD_DATE=`date +%m-%d-%Y -d "7 day ago"`
BACKUP_DIR=/var/backups/containers
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p $BACKUP_DIR
fi
for i in $(ls /var/snap/lxd/common/lxd/containers); do
echo "=============================="
echo Taking snapshot of containers $i .....
echo "=============================="
/snap/bin/lxc snapshot $i $i-$DATE
if lxc image list | grep "$i-$DATE-backup"
then
echo "Image is present, skipping job"
else
echo "=============================="
echo Publishing $i to local image server .....
echo "=============================="
/snap/bin/lxc publish $i/$i-$DATE --alias $i-$DATE-backup
fi
if [ -f $BACKUP_DIR/$i-$DATE-backup.tar.gz ];
then
echo "Backup file is present, skipping job"
else
echo "=============================="
echo Exporting $i to $BACKUP_DIR .....
echo "=============================="
/snap/bin/lxc image export $i-$DATE-backup $BACKUP_DIR/$i-$DATE-backup
fi
echo "=============================="
echo Removing backup files older than 7 days .....
echo "=============================="
find $BACKUP_DIR -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +
echo "=============================="
echo Removing backup images older than 7 days .....
echo "=============================="
/snap/bin/lxc image delete $i-$OLD_DATE-backup
echo "=============================="
echo Removing snapshot images older than 7 days .....
echo "=============================="
/snap/bin/lxc delete $i/$i-$OLD_DATE
echo "=============================="
echo Setting correct file ownership in $BACKUP_DIR .....
echo "=============================="
find $BACKUP_DIR/ -type f -exec chown root:root {} \;
find $BACKUP_DIR/ -type f -exec chmod 0640 {} \;
find $BACKUP_DIR/ -type d -exec chmod 0640 {} \;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment