Skip to content

Instantly share code, notes, and snippets.

@schnapster
Created January 21, 2018 15:56
Show Gist options
  • Save schnapster/b3f270fc5a1c6e38faa22748a6a731f1 to your computer and use it in GitHub Desktop.
Save schnapster/b3f270fc5a1c6e38faa22748a6a731f1 to your computer and use it in GitHub Desktop.
Backup postgres database to backblaze b2
#!/bin/bash
# this requires the backblaze CLI tool to be installed (pip install b2)
# pass 4 args:
# - database name (needs to exist in postgres)
# - app name (meta information)
# - bucket name (target of the upload)
# - file containing b2 credentials (it will be sourced and needs to set B2_ACCOUNT_ID and B2_APP_KEY)
#
# example: ./pg_b2_backup.sh db app backups-daily ~/b2_creds
#
# example for a daily cron job backing up database "db" of app "app" to b2 bucket "daily-backups":
# 20 4 * * * cd ~/scripts && ./pg_b2_backup.sh db app daily-backups ~/b2_creds &>> ~/logs/backups.log
set -e
echo $(date)
# Verify we are root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit 1
fi
DB=$1
APP=$2
BUCKET=$3
echo "Backing up db ${DB} of app ${APP} to bucket ${BUCKET}."
source $4
DUMPDIR="/tmp"
#will look like: app_db_2017-12-31.dump
FILENAME=${APP}_${DB}_$(date +%Y-%m-%d).dump
INFO="--info app=${APP} --info db=${DB}"
mkdir -p ${DUMPDIR}
# cleanup any old backups
if [ -f "${DUMPDIR}/${FILENAME}" ]; then
rm -f "${DUMPDIR}/${FILENAME}"
fi
# dump it
su - postgres -c "pg_dump ${DB} > ${DUMPDIR}/${FILENAME}"
# calculate sha1 sum
SHA1=$(sha1sum ${DUMPDIR}/${FILENAME} | sed -En "s/^([0-9a-f]{40}).*/\1/p")
#log in to backblaze
b2 authorize-account ${B2_ACCOUNT_ID} ${B2_APP_KEY}
# upload it
b2 upload-file --sha1 ${SHA1} \
${INFO} \
--noProgress \
${BUCKET} \
${DUMPDIR}/${FILENAME} \
${FILENAME}
#log out
b2 clear-account
# make sure file still exists and clean it up
if [ -f "${DUMPDIR}/${FILENAME}" ]; then
rm -f "${DUMPDIR}/${FILENAME}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment