-
-
Save azaitsev/1e5ff7c2424f231c618bd493d6c4bcc2 to your computer and use it in GitHub Desktop.
Backup postgres database to backblaze b2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# this requires the backblaze CLI tool to be installed (pip install b2) | |
# pass 4 args: | |
# - database name (needs to exist in postgres) | |
# - 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 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 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 | |
BUCKET=$2 | |
echo "Backing up db ${DB} to bucket ${BUCKET}." | |
source $3 | |
DUMPDIR="/tmp/${DB}" | |
#will look like: app_db_2017-12-31.dump | |
FILENAME=${DB}_$(date +%Y-%m-%d).dump | |
INFO="--info app=${DB} --info db=${DB}" | |
mkdir -p ${DUMPDIR} | |
chown postgres:postgres -R ${DUMPDIR} | |
# cleanup any old backups | |
if [ -f "${DUMPDIR}/${FILENAME}" ]; then | |
rm -f "${DUMPDIR}/${FILENAME}" | |
fi | |
# dump it | |
su - postgres -c "pg_dump -Fc ${DB} > ${DUMPDIR}/${FILENAME}" | |
# calculate sha1 sum | |
SHA1=$(sha1sum ${DUMPDIR}/${FILENAME} | sed -En "s/^([0-9a-f]{40}).*/\1/p") | |
#log in to backblaze | |
/usr/local/bin/b2 authorize-account ${B2_ACCOUNT_ID} ${B2_APP_KEY} | |
# upload it | |
/usr/local/bin/b2 upload-file --sha1 ${SHA1} \ | |
${INFO} \ | |
--noProgress \ | |
${BUCKET} \ | |
${DUMPDIR}/${FILENAME} \ | |
${FILENAME} | |
#log out | |
/usr/local/bin/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