Last active
October 30, 2019 18:12
-
-
Save gadelkareem/91b4d21ec20e2d209804da93a277b9d3 to your computer and use it in GitHub Desktop.
PostgreSQL backup restore script https://gadelkareem.com/2019/06/11/database-backup-restore-via-s3/
This file contains 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
#!/usr/bin/env bash | |
set -euo pipefail | |
cd `dirname $0` | |
# lock it | |
PIDFILE="/tmp/$(basename "${BASH_SOURCE[0]%.*}.pid")" | |
exec 200>${PIDFILE} | |
flock -n 200 || ( echo "${BASH_SOURCE[0]} script is already running. Aborting . ." && exit 1 ) | |
PID=$$ | |
echo ${PID} 1>&200 | |
TIMESTAMP=$(date '+%Y_%m_%d__%H_%M_%S') | |
mkdir -p /var/backups/databases | |
cd /var/backups/databases | |
function backup(){ | |
DB=${1} | |
FILENAME=${TIMESTAMP}.dump | |
ROUTE="${DB}/${ENV}" | |
DIR=/var/backups/databases/${ROUTE} | |
FILE="${DIR}/${FILENAME}" | |
mkdir -p "${DIR}" | |
cd "${DIR}" | |
echo Backing up ${DB} | |
if [ "${DB}" == "all" ]; then | |
FILE="${FILE}.bz2" | |
pg_dumpall -U postgres -h localhost --no-password | bzip2 > ${FILE} | |
else | |
pg_dump -U postgres --no-owner --no-acl -h localhost -f ${FILE} --format=custom --compress=9 --no-password ${DB} | |
fi | |
echo Uploading ${DB} | |
/usr/bin/s3cmd put ${FILE} s3://backups/db/${ROUTE}/${FILENAME} | |
rm -f ${FILE} | |
echo ${FILENAME} > latest | |
/usr/bin/s3cmd put latest "s3://backups/db/${ROUTE}/latest" | |
rm -f latest | |
} | |
function restore(){ | |
DB=${1} | |
ROUTE="${DB}/${ENV}" | |
DIR=/var/backups/databases/${ROUTE} | |
mkdir -p "${DIR}" | |
cd "${DIR}" | |
/usr/bin/s3cmd get --force s3://backups/db/${ROUTE}/latest | |
/usr/bin/s3cmd get --force s3://backups/db/${ROUTE}/$(cat latest) - > latest.dump | |
echo Restoring ${DB} | |
if [ "${DB}" == "all" ]; then | |
bzcat latest.dump | psql -U postgres | |
else | |
pg_restore -v --jobs=4 -U postgres --no-owner -d ${DB} latest.dump | |
fi | |
rm -f latest | |
rm -f latest.dump | |
} | |
for i in "${@:2}" | |
do | |
$1 $i | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment