Skip to content

Instantly share code, notes, and snippets.

@aambert
Forked from hackedunit/db_backup.sh
Created April 2, 2020 09:16
Show Gist options
  • Save aambert/8b17c5e21906d32294bb5e3df9d05038 to your computer and use it in GitHub Desktop.
Save aambert/8b17c5e21906d32294bb5e3df9d05038 to your computer and use it in GitHub Desktop.

Revisions

  1. @hackedunit hackedunit revised this gist Oct 11, 2018. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions db_backup.sh
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,7 @@
    #!/bin/bash

    # Requires azure-cli to be installed

    source $HOME/.profile

    if [ "${POSTGRES_HOST}" = "" ]; then
  2. @hackedunit hackedunit created this gist Oct 11, 2018.
    49 changes: 49 additions & 0 deletions db_backup.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #!/bin/bash

    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