Python Script to take backup of Ec2 Volume with days retention

Assumption:

  1. We have access key and secret key which has a privilege to create snapshot, delete snapshot, list volumes,etc.,
  2. 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 🙂

admin

Our team has expertise across software and web development, WordPress, e-commerce, mobile applications, UI/UX, cloud and infrastructure, DevOps, CI/CD, API integration, security, testing, automation, and technical support. The team also works with AI-based software solutions, LLMs, AI workflows, AI agents, and intelligent application development to help businesses automate processes and build smarter digital solutions. We focus on developing, deploying, maintaining, and optimising secure, scalable, and reliable technology solutions while helping businesses adopt modern technologies and drive digital transformation.

Leave a Reply

Scroll to Top