Skip to content

Instantly share code, notes, and snippets.

@moranbw
Created August 3, 2020 03:27
Show Gist options
  • Save moranbw/e34ba73ef8eefa52494c95dd6809fc24 to your computer and use it in GitHub Desktop.
Save moranbw/e34ba73ef8eefa52494c95dd6809fc24 to your computer and use it in GitHub Desktop.
Get a database dump via psql and push to S3
#!/usr/bin/env bash
if [ "$1" == "" ]; then
echo "Bucket name required"
exit 1
fi
DATE=$(date +%Y%m%d_%H%M)
DB_NAME=$PGDATABASE
BUCKET=$1
PSQL_HOST=$PGHOST
PSQL_USER=$PGUSER
if [ "$PSQL_HOST" == "" ]; then
PSQL_HOST=localhost
fi
if [ "$PSQL_USER" == "" ]; then
PSQL_USER=postgres
fi
# Execute a database lookup
(psql -U "$PSQL_USER" -h "$PSQL_HOST" -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME")
EXISTS=$?
if [[ "$EXISTS" != 0 ]]
then
echo "Database does not exist"
exit 1
fi
echo "Database exists. Preparing dump"
OUTPUT_FILE="/tmp/$DB_NAME-dump_$DATE.sql.bz2"
pg_dump -U "$PSQL_USER" -h "$PSQL_HOST" "$DB_NAME" > "/tmp/$DB_NAME-dump_$DATE.sql"
bzip2 -c "/tmp/$DB_NAME-dump_$DATE.sql" > "$OUTPUT_FILE"
aws s3 cp "$OUTPUT_FILE" "s3://$BUCKET/dumps/"
# Remove temporary files
rm "$OUTPUT_FILE"
rm "/tmp/$DB_NAME-dump_$DATE.sql"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment