Skip to content

Instantly share code, notes, and snippets.

@chiedo
Last active October 19, 2016 13:57
Show Gist options
  • Save chiedo/f63bb4c3ba961c549904 to your computer and use it in GitHub Desktop.
Save chiedo/f63bb4c3ba961c549904 to your computer and use it in GitHub Desktop.
AWS EC2 EBS Backups
"""
Run this backup script daily with a cronjob. Will Store 4 backups of each at a time.
It could obviously be modified to support more backups. It is written in a quick and dirty fashion.
... It's a backup script that works. Who cares?
dependencies:
- EC2 API Tools
Be sure to set up environment variables for AWS_ACCESS_KEY and AWS_SECRET_KEY
"""
import subprocess
import datetime
import os
# Fill in the source and destination regions.
source_region = ''
dest_region = ''
os.environ['EC2_URL'] = "ec2.%s.amazonaws.com" %(dest_region)
# Fill in the volume ID (eg. vol-340b5566)
volume_id = ""
# Create useful backup name (eg. burgerking.com daily root backup)
backup_name = ""
# maximum number of backups to keep
max_backups = 4
# String used by grep to keep backups. LEAVE BLANK.
backups_to_keep = ""
for x in range(0, max_backups):
backups_to_keep += (datetime.datetime.now() - datetime.timedelta(days=(x + 1))).strftime("%Y-%m-%d")
if(x + 1 < max_backups):
backups_to_keep += "|"
# Delete all snap shots generated by this script not taken within the past four days
subprocess.call("ec2-describe-snapshots --region %s | sort -k 5 | grep -vE '%s' | grep -E '%s' | awk '{print $2}' | xargs -n 1 -t ec2-delete-snapshot --region %s"
% (dest_region, backups_to_keep, backup_name, dest_region), shell=True)
#Output all snapshots
subprocess.call("ec2-describe-snapshots --region %s | sort -k 5 | grep '%s' | grep 'completed' | tail -1 | awk '{print $2}' | xargs -n 1 -t ec2-copy-snapshot --source-region %s --region %s --description '%s' -s" % (source_region, volume_id, source_region, dest_region, backup_name), shell=True)
"""
Use this https://github.com/colinbjohnson/aws-missing-tools/tree/master/ec2-automate-backup
"""
@chiedo
Copy link
Author

chiedo commented Oct 12, 2015

For this to work, its crucial that the time zone is the same as your AWS instance's
http://unix.stackexchange.com/questions/110522/timezone-setting-in-linux

@chiedo
Copy link
Author

chiedo commented Oct 12, 2015

To install the API tools, see this.
https://help.ubuntu.com/community/EC2StartersGuide

@chiedo
Copy link
Author

chiedo commented Oct 12, 2015

I like to run the script in a shell wrapper like each script and run the wrapper. Name that whatever you want.

export JAVA_HOME=""
export EC2_HOME=
export PATH=$PATH:$EC2_HOME/bin
export AWS_ACCESS_KEY=
export AWS_SECRET_KEY=
python YOUR_PATH/create-daily-ebs-backups.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment