Skip to content

Instantly share code, notes, and snippets.

@dioncodes
Last active February 19, 2021 17:22
Show Gist options
  • Save dioncodes/dfc35bf05eadfb7085863be00b183247 to your computer and use it in GitHub Desktop.
Save dioncodes/dfc35bf05eadfb7085863be00b183247 to your computer and use it in GitHub Desktop.
Automatic AWS Database Backup

AWS (S3) DB Backup Script

  • Requirements: aws-cli
  • Add the following to your crontab for an hourly backup:

0 * * * * /path/to/db-backup-exec.sh >> /var/log/db-aws-backup.log

Make sure to configure the S3 bucket to remove old backups after some time!

#!/usr/bin/env bash
AWS_ACCESS_KEY_ID="ABC" \
AWS_SECRET_ACCESS_KEY="ABC123" \
AWS_DEFAULT_REGION="eu-central-1" \
S3_BUCKET="example-bucket" \
MYSQL_HOST="127.0.0.1" \
MYSQL_PORT=3306 \
MYSQL_DB="mysql_db" \
MYSQL_USER="mysql_user" \
MYSQL_PASS="mysql_pw" \
/path/to/db-backup.sh
#!/bin/bash
cd /tmp
file=$(date +%Y-%m-%d-%H-%M).sql
mysqldump \
--host ${MYSQL_HOST} \
--port ${MYSQL_PORT} \
--user ${MYSQL_USER} \
--password="${MYSQL_PASS}" \
${MYSQL_DB} > ${file}
if [ "${?}" -eq 0 ]; then
gzip ${file}
aws s3 cp ${file}.gz s3://${S3_BUCKET}
rm ${file}
rm ${file}.gz
else
echo "Error backing up mysql"
exit 255
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment