Skip to content

Instantly share code, notes, and snippets.

@bottlenecked
Created May 11, 2021 11:29
Show Gist options
  • Save bottlenecked/e9c54962a4ca2009834b879c5bc31fdb to your computer and use it in GitHub Desktop.
Save bottlenecked/e9c54962a4ca2009834b879c5bc31fdb to your computer and use it in GitHub Desktop.
A script for fetching db dumps locally
#! /bin/bash
Help()
{
echo
echo "A script for fetching db dumps locally"
echo
echo "Usage: dbdump <ENV> <SYSTEM> <DATABASE>"
echo
echo "Example:"
echo
echo "$ dbdump staging service service-cs-selection"
echo
echo "The above command will create a local file named <DATABASE>.<ENV>.dump.<TIMESTAMP>.sql"
echo
echo "You can then import it locally, e.g. with:"
echo
echo "psql <LOCAL_DEV_DB> < <DUMP_FILE>"
}
echoerr() { printf "\e[31;1m%s\e[0m\n" "$*" >&2; }
while getopts ":h" option; do
case $option in
h) # display Help
Help
exit;;
esac
done
if [ "$#" -ne 3 ]; then
echoerr "This script expects 3 parameters but $# were given"
Help
exit 1
fi
ENV=$1
SYSTEM=$2
DATABASE=$3
RUBY_SCRIPT="$(cat <<RUBY_SCRIPT
(domain, path) = gets.split("//")
path_elems = path.split("/")
path_elems[-1] = "$DATABASE"
path = path_elems.join("/")
puts "#{domain}//#{path}"
RUBY_SCRIPT
)"
echo "creating database gzipped dump..."
KUBERNETES_COMMAND="env | grep -i "$SYSTEM"_$ENV | awk -F'=' '{print \$2}' | ruby -e '$RUBY_SCRIPT' | xargs -I% pg_dump % | gzip -c > /tmp/dump.sql.gz && echo \$HOSTNAME"
PODNAME=$(kubectl exec deployment/infrastructure-res-aws-databasetoolbox -- sh -c "$KUBERNETES_COMMAND")
echo "copying dump file locally..."
FILENAME="$DATABASE.$ENV.dump.$(date +%s%3).sql"
kubectl cp $PODNAME:/tmp/dump.sql.gz ./$FILENAME.gz
echo "cleaning up remote dump file..."
kubectl exec deployment/infrastructure-res-aws-databasetoolbox -- rm /tmp/dump.sql.gz
echo "unzipping local dump..."
gunzip $FILENAME.gz
echo "Done. Sample contents of ./$FILENAME :"
echo
head -n6 $FILENAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment