Skip to content

Instantly share code, notes, and snippets.

@hackedunit
Last active May 12, 2024 13:45
Show Gist options
  • Save hackedunit/01934c02f1bae74f995d9dd76208fd3b to your computer and use it in GitHub Desktop.
Save hackedunit/01934c02f1bae74f995d9dd76208fd3b to your computer and use it in GitHub Desktop.
Backup PostgreSQL dump to Microsoft Azure Blob Storage
#!/bin/bash
# Requires azure-cli to be installed
source $HOME/.profile
if [ "${POSTGRES_HOST}" = "" ]; then
if [ -n "${POSTGRES_PORT_5432_TCP_ADDR}" ]; then
POSTGRES_HOST=$POSTGRES_PORT_5432_TCP_ADDR
POSTGRES_PORT=$POSTGRES_PORT_5432_TCP_PORT
else
echo "You need to set the POSTGRES_HOST environment variable."
exit 1
fi
fi
if [ "${POSTGRES_DB}" = "" ]; then
echo "You need to set the POSTGRES_DB environment variable."
exit 1
fi
if [ "${POSTGRES_USER}" = "" ]; then
echo "You need to set the POSTGRES_USER environment variable."
exit 1
fi
if [ "${POSTGRES_PASSWORD}" = "" ]; then
echo "You need to set the POSTGRES_PASSWORD environment variable or link to a container named POSTGRES."
exit 1
fi
if [ -n $POSTGRES_PASSWORD ]; then
export PGPASSWORD=$POSTGRES_PASSWORD
fi
echo "dumping $POSTGRES_DB"
pg_dump --host=$POSTGRES_HOST --port=$POSTGRES_PORT --username=$POSTGRES_USER $POSTGRES_DB | gzip > "/tmp/$POSTGRES_DB.gz"
if [ $? == 0 ]; then
/usr/bin/az storage blob upload --name "$POSTGRES_DB-$(date +%s).gz" --file /tmp/$POSTGRES_DB.gz --container-name $AZURE_STORAGE_CONTAINER --connection-string "DefaultEndpointsProtocol=https;AccountName=$AZURE_STORAGE_ACCOUNT;AccountKey=$AZURE_STORAGE_ACCESS_KEY;EndpointSuffix=core.windows.net;"
if [ $? == 0 ]; then
echo "success!"
rm /tmp/$POSTGRES_DB.gz
else
>&2 echo "couldn't transfer $POSTGRES_DB.gz to Azure"
fi
else
>&2 echo "couldn't dump $POSTGRES_DB"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment