Skip to content

Instantly share code, notes, and snippets.

@rharriso
Created September 16, 2019 02:51
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Backing Up a database with an AWS EC2 Proxy
#!/bin/bash
SSH_KEY=[PATH TO KEYS]
PROXY_SERVER_ID=[EC2 SERVER ID] # server ID remains when instance is stopped
BACKUP_DIR=[EXTERNAL BACK DIRECTORY]
# Stop the server on exit
trap "echo \"Stopping ec2 instance\"; aws ec2 stop-instances --instance-ids $PROXY_SERVER_ID >> /dev/null 2>&1" EXIT SIGINT SIGTERM
echo "Starting ec2 instance"
aws ec2 start-instances --instance-ids $PROXY_SERVER_ID >> /dev/null || exit
echo "waiting for ec2 instance"
aws ec2 wait instance-running --instance-ids $PROXY_SERVER_ID || exit 1
IP_ADDRESS=$(aws ec2 describe-instances --instance-ids $PROXY_SERVER_ID | jq -r '.Reservations[0].Instances[0].NetworkInterfaces[0].Association.PublicIp')
echo "say hello to backup proxy: $IP_ADDRESS"
n=0
until [ $n -ge 5 ]
do
# break if connection worked
ssh -oStrictHostKeyChecking=no ubuntu@$IP_ADDRESS -i $SSH_KEY "echo 'hello'" && break
n=$[$n+1]
echo "Connection Failed Trying again: Attempt $n"
sleep 3
done
# Exit if we never succeeded
if [ $n -ge 5 ]
then
exit 1
fi
echo "Connection successful"
DB_SECRET_PATH=[DB PATH WITHIN AWS SECRETS]
SECRET=$(aws secretsmanager get-secret-value --secret-id $DB_SECRET_PATH | jq -r '.SecretString')
DBUSER=$(echo $SECRET | jq '.username')
DBNAME=$(echo $SECRET | jq '.dbname')
PASS=$(echo $SECRET | jq '.password')
HOST=$(echo $SECRET | jq '.host')
DATE_STR=$(date +"%y-%m-%d")
ssh ubuntu@$IP_ADDRESS -i $SSH_KEY \
"echo $PASS | pg_dump --host=$HOST --user=$DBUSER $DBNAME | gzip" \
> $BACKUP_DIR/db-name.dump.$DATE_STR.sql.gz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment