Backup you on-prem/local #PostgreSQL database to cloud #AWS #RDS snapshot

backup for $0.026 + $0.125 per GB-month

Total costs of the backup operation: $0.026 + $0.125 per GB-month

Script below will do the following steps:

  1. create PostgresSQL AWS RDS t1.micro instance
  2. wait till instance started by using aws rds describe-db-instances
  3. get AWS RDS instance address
  4. copy database
  5. create AWS RDS instance snapshot and terminate instance by using aws rds delete-db-instance
  6. send notification by using AWS SNS service

Prerequisites:

#!/bin/bash
SNSTOPIC=arn:aws:sns:us-east-1:000000000000:MYTOPIC
RDSINSTANCE=MYBACKUP
_now=$(date +"%d%m%Y")
BACKUPNAME="$RDSINSTANCE$_now"
DATABASE=MYDB
DBADMIN=admin
export PGPASSWORD=MYPASSWORD

# create RDS instance
aws rds create-db-instance --db-instance-identifier $RDSINSTANCE --allocated-storage 5 --db-instance-class db.t1.micro --no-multi-az --engine postgres --master-username $DBADMIN --master-user-password $PGPASSWORD --db-name $DATABASE --backup-retention-period 0

# wait till instance started
while [ `aws rds describe-db-instances --db-instance-identifier $RDSINSTANCE | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DBInstances"][0]["DBInstanceStatus"]'` != "available" ]; do sleep 10; done

# get instance address
AWSHOST=`aws rds describe-db-instances --db-instance-identifier $RDSINSTANCE | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["DBInstances"][0]["Endpoint"]["Address"]'`

# copy database
pg_dump -U postgres dbname=$DATABASE | psql --host=$AWSHOST --username=$DBADMIN --dbname=$DATABASE

# terminate instance and create snapshot
aws rds delete-db-instance --db-instance-identifier $RDSINSTANCE --final-db-snapshot-identifier $BACKUPNAME

# send notification
aws sns publish --topic-arn $SNSTOPIC --subject 'AWS RDS BACKUP' --message 'Done'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s