Skip to content

Instantly share code, notes, and snippets.

@bishwanathjha
Created December 3, 2019 10:16
Show Gist options
  • Save bishwanathjha/d9f22d7525996052724cb50ec2a100c0 to your computer and use it in GitHub Desktop.
Save bishwanathjha/d9f22d7525996052724cb50ec2a100c0 to your computer and use it in GitHub Desktop.
Bash script to backup mysql database, upload backup to aws s3 and notify on slack
#!/bin/bash
# Database credentials
user="db_user"
password="db_password"
host="127.0.0.1"
db="database"
prefix="db"
# Other options
backup_path="/home/ec2-user"
# Set the file name
date=$(TZ=Asia/Kolkata date +"%d-%b-%Y")
datetime=$(TZ=Asia/Kolkata date +"%d-%b-%Y-%H-%M-%S")
# Set default file permissions
umask 022
# Set the start time for profiling
start=`date +%s`
# Dump database into SQL file and zip it to reduce size
mysqldump --user=$user --password=$password --host=$host --databases $db --skip-lock-tables | gzip -c > $backup_path/$prefix-$datetime.sql.gz
# Set the end time for profiling
end=`date +%s`
# Get the backup file size
timetaken=`expr $end - $start`
FILESIZE=$(ls -lah "$backup_path/$prefix-$datetime.sql.gz" | awk '{ print $5}')
# Upload the backup file to aws S3 folder under specific date
aws s3 cp $backup_path/$prefix-$datetime.sql.gz s3://your_s3_bucket_name/$date/
# Remove the backup file from local machine
rm $backup_path/$prefix-$datetime.sql.gz
# Post the altert on slack
curl -X POST --data-urlencode "payload={'username': 'DBBackupBOT', 'text': 'DB Backup (${FILESIZE}) is successful in ${timetaken} seconds', 'icon_emoji': ':ghost:'}" https://hooks.slack.com/services/XXXXXXXXXXXXX/XXXXXXXXXXXX/XXXXXXXXXXXXXXXXX
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment