Automating EC2 with AWS Lambda Using Boto3- Lab 4

Shivani Singh
2 min readNov 29, 2023

Problem Statement:
In a dynamic and distributed AWS environment, it is crucial to establish a robust backup strategy for Amazon Elastic Compute Cloud (EC2) instances’ data. The challenge is to implement an automated solution that creates regular backups (snapshots) of Amazon Elastic Block Store (EBS) volumes attached to EC2 instances based on specified criteria. This solution should be designed to run as an AWS Lambda function, ensuring efficient and scalable backup operations across multiple regions.

#Import necessary modules. datetime is used to generate a timestamp, and boto3 is the AWS SDK for Python.

from datetime import datetime
import boto3

#Define the main Lambda function, lambda_handler. The script starts by creating an EC2 client and obtaining a list of AWS regions
def lambda_handler(event, context):
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]

#Iterates through each region and prints a message indicating the current region. It then creates an EC2 resource for the specified region
for region in regions:
print('Instances in EC2 Region {0}:'.format(region))
ec2 = boto3.resource('ec2', region_name=region)

instances = ec2.instances.filter(
Filters=[
{'Name': 'tag:backup', 'Values': ['true']}
]
)

#Filters instances based on a tag (backup:true). This is used to identify instances that should be included in the backup process.
timestamp = datetime.utcnow().replace(microsecond=0).isoformat()

#Generates a timestamp in UTC format, without microseconds.
for i in instances.all():
for v in i.volumes.all():
desc = 'Backup of {0}, volume {1}, created {2}'.format(i.id, v.id, timestamp)
print(desc)
#Iterates through all instances and their volumes, creating a description for the snapshot based on the instance ID, volume ID, and timestamp
snapshot = v.create_snapshot(Description=desc)
print("Created Snapshot:", snapshot.id)

The Lambda function scans EC2 instances in each region, identifies instances with the ‘backup:true’ tag, creates snapshots for their volumes, and prints information about the backup process, including the description and snapshot ID. This script is designed to be triggered periodically or in response to specific events for regular backup tasks.

Hope this was helpful
See you in the next lab
Happy Learning!
Shivani S

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Shivani Singh
Shivani Singh

Written by Shivani Singh

DevOps Engineer, Passionate for new tools and Technology!

No responses yet

Write a response