Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Last active November 14, 2018 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaytaylor/48a57ec1d8a09c231af27b2b111f973c to your computer and use it in GitHub Desktop.
Save jaytaylor/48a57ec1d8a09c231af27b2b111f973c to your computer and use it in GitHub Desktop.
Utility for backing up a remote Andromeda Postgres DB. Preserves only the past X database dumps.
#!/usr/bin/env bash
##
# @author J. Elliot Taylor (@jaytaylor)
#
# @date 2018-11-14
#
# @description Andromeda postgres DB remote backup utility.
#
set -o errexit
set -o pipefail
set -o nounset
#set -x
export SSH_HOST='web'
export DB_NAME='andromeda'
export LOCAL_PATH='/datastore/backups/andromeda/db'
export PRESERVE_NUM_BACKUPS=14
function backupDB() {
mkdir -p "${LOCAL_PATH}"
# shellcheck disable=SC2029
ssh -C "${SSH_HOST}" pg_dump "${DB_NAME}" \
| gzip > "${LOCAL_PATH}/${DB_NAME}.$(date +%Y%m%d%H%M%S).sql.gz"
}
function cleanupOld() {
local expired
local ifsBak
mkdir -p "${LOCAL_PATH}"
cd "${LOCAL_PATH}"
# Preserve only the newest X files. Do it in a way which is safe for files
# containing spaces in the name.
#
# `find' is used than `ls' to better handle non-alphanumeric filenames.
#
# Thanks to https://stackoverflow.com/a/16962596/293064 for the
# `cut --complement' trick.
expired="$(find "${LOCAL_PATH}" -mindepth 1 -maxdepth 1 -printf "%T+ %p\n" | sort --reverse | cut -d ' ' -f 2- | awk "NR>${PRESERVE_NUM_BACKUPS}")"
if [ -n "${expired}" ] ; then
ifsBak="${IFS:-}"
IFS=$'\n'
# shellcheck disable=SC2001
echo -e "INFO: Removing $(echo "${expired}" | wc -l) file(s):\n$(echo "${expired}" | sed 's/^/ /')" 1>&2
for f in ${expired} ; do
rm -rf "${f}"
done
export IFS="${ifsBak}"
fi
cd -
}
if [ "${BASH_SOURCE[0]}" = "${0}" ] ; then
# Only auto-run when being executed (and don't auto-run functions when being
# sourced).
backupDB
cleanupOld
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment