Python Script to take backup of Ec2 Volume with days retention
Assumption:
- We have access key and secret key which has a privilege to create snapshot, delete snapshot, list volumes,etc.,
- The script will keep 4 days retention and delete the old backups.
#!/usr/bin/python
#Author:Dhanasekaran N
#Email:dhanasekaran.n16@gmail.com,support@pheonixsolutions.com
#Usage:python create_aws_snapshot.py AWS_TAG_NAME
#Version:1.0
#Here come I.......
from datetime import datetime, timedelta
import datetime
import time
from dateutil import parser
import sys,os,time,re,argparse
import boto,boto.ec2,boto.utils
conn=boto.ec2.connect_to_region('ap-southeast-1', aws_access_key_id='XXXXXXXXX',aws_secret_access_key='xxxxxxxxxxxxxxx');
reservations=conn.get_all_instances()
all_volumes_info = conn.get_all_volumes()
all_snapshot = conn.get_all_snapshots()
##Modify the retention period
date_4_days_ago=datetime.datetime.now() - datetime.timedelta(days=4)
command_line_instance=sys.argv[1];
for name in reservations:
for instance in name.instances:
aws_inst_name=instance.tags.get("Name")
#print aws_inst_name
if(aws_inst_name == command_line_instance):
print "perfect" + command_line_instance;
for volumes in all_volumes_info:
if volumes.attach_data.instance_id == instance.id:
print "Taking backup of volumes";
print "Instance ID:%s" %(instance.id);
print "Volume ID:%s" %(volumes.id);
print "Instance Name:%s" %(aws_inst_name);
for snap_delete in all_snapshot:
if(snap_delete.volume_id == volumes.id):
if parser.parse(snap_delete.start_time).date() < date_4_days_ago.date():
conn.delete_snapshot(snap_delete.id);
Usage:
python aws_create_snapshot.py AWS_TAG_NAME
Next time with all the instance with configuration 🙂
