Last active
January 9, 2024 14:33
-
-
Save RomanGorbatko/69473ff8a146bc5a9b9a23896597a233 to your computer and use it in GitHub Desktop.
PostgreSQL daily backup and store to Digitalocean Spaces or Amazon 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
#!/bin/bash | |
BACKUP_DIR=/tmp/pg_backup | |
DAYS_TO_KEEP=2 | |
FILE_SUFFIX=_pg_backup.sql | |
DATABASE=**database-name** | |
USER=**database-user** | |
SPACE=**bucket-name** | |
FILE=`date +%y%m%d-%H_%M_%S`${FILE_SUFFIX} | |
OUTPUT_FILE=${BACKUP_DIR}/${FILE} | |
dumpAndZip(){ | |
echo "Creating SQL dump" | |
pg_dump -U ${USER} ${DATABASE} -F p -f ${OUTPUT_FILE} | |
echo "Gathering files" | |
if gzip ${OUTPUT_FILE}; then | |
echo "Done gathering files" | |
return 0 | |
else | |
echo "Failed to gather files" | |
return 1 | |
fi | |
} | |
movetoSpace(){ | |
echo "Moving to Space" | |
if s3cmd put --quiet ${OUTPUT_FILE}.gz s3://$SPACE; then | |
echo "Done moving files to s3://"$SPACE"" | |
# prune old backups | |
find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*${FILE_SUFFIX}.gz" -exec rm -rf '{}' ';' | |
return 0 | |
else | |
echo "Failed to move files to the Space" | |
return 1 | |
fi | |
} | |
if dumpAndZip; then | |
movetoSpace | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment