AndyJarrett

Bash script to backup a MySQL RDS dump to S3

This post has been updated:

www.andyjarrett.co.uk/2016/08/02/secured-bash-script-to-backup-a-mysql-rds-dump-to-s3/


Amazon RDS has nice backup plan in place but you don't have access to these and its a good pratice to store a "dump" yourself. This simple script does that by running MySQLDump via CRON to get the data out of the RDS, GZips it up, and stores it on S3.

1) Install s3cmd

sudo apt-get install -y s3cmd

2) Configure s3cmd

$ s3cmd --configure

3) Create your new script

$ sudo nano mysqlBackUp.sh

4) Add this to mysqlBackUp.sh

#!/bin/bash
SQLDUMP="$(date +'%Y%m%d%H%M').sql.gz"

echo "Creating backup of database to $SQLDUMP"  
mysqldump --host x.xx-xx-x.rds.amazonaws.com -u Username -pPassword --databases YourDatabaseName | gzip -9 > $SQLDUMP

echo "Dump Zipped up"

echo "Uploading zipped dump to the Amazon S3 bucket…"  
s3cmd put $BACKUPNAME s3://bucketname/backup/folder/$BACKUPNAME

echo "Removing the backup file $SQLDUMP"  
rm $BACKUPNAME

echo "WooHoo! All done"  

5) Make it executable

$ sudo chmod 700 mysqlBackUp.sh

6) Create a root CRON job

$ sudo crontab -e
# Add the following to CRON to run daily at midnight
0 0 * * * /path/to/backup.sh

6.a) You might need to copy the .s3cfg to /root/ for Cron to run properly

sudo cp .s3cfg /root/.s3cfg

That's it you're all set.