Introduction

Amazon Elastic Block Store (Amazon EBS) snapshots provide a reliable way to back up the data stored on an Amazon EC2 instance’s volumes. Automating snapshot creation helps protect critical data, simplifies disaster recovery, and reduces the effort required for manual backups. This article demonstrates a Python script that creates EBS snapshots for all volumes attached to an EC2 instance by specifying the instance’s Name tag.

Prerequisites

Before running the script, ensure the following requirements are met:

  • An active AWS account.
  • Python installed on the system.
  • The boto Python library installed.
  • AWS Access Key ID and Secret Access Key with permission to create EBS snapshots.
  • The target EC2 instance must have a Name tag.
  • Network connectivity to AWS APIs.
  • The AWS region in the script should match the region where the EC2 instance is running.

IMPLEMENTATION

Assumption:

  1. AWS access key has a privilege to create snapshot.
  2. Aws Tag name has to be passed as an argument.
  3. Replace aws access key and secret key with proper keys
#!/usr/bin/pythonmaybe
#Author:Dhanasekaran N
#Email:dhanasekaran.n16@gmail.com
#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='XXXXXXXXXXXX',aws_secret_access_key='XXXXXXXXXXXXXX');

reservations=conn.get_all_instances()
all_volumes_info = conn.get_all_volumes()


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";
					snapshot=conn.create_snapshot(volumes.id,command_line_instance);
					
					print "Instance ID:%s" %(instance.id);
					print "Volume ID:%s" %(volumes.id);
					print "Instance Name:%s" %(aws_inst_name);
					print "Snapshot ID:%s" %(snapshot.id);

Usage
python aws_create_snapshot.py AWS_INSTANCE_NAME

Conclusion

Using a Python script to automate Amazon EBS snapshot creation is an efficient way to back up EC2 instance volumes. By simply providing the EC2 instance’s Name tag, the script identifies all attached EBS volumes and creates snapshots for each of them. This approach helps streamline backup operations and can be further enhanced by implementing features such as snapshot retention, automated scheduling with cron or AWS EventBridge, logging, notifications, and the use of IAM roles instead of hardcoded AWS credentials for improved security.

Leave a Reply