Automating EC2 with AWS Lambda Using Boto3- Lab 3

Shivani Singh
2 min readNov 28, 2023

Problem statement:

Your organization manages a dynamic AWS infrastructure with Amazon Machine Images (AMIs) spread across multiple regions. To ensure efficient resource utilization and cost management, you need an automated solution to identify and delete aged AMIs. The goal is to implement an AWS Lambda function that iterates through all regions, identifies AMIs older than a specified threshold (e.g., 2 days), and deregisters (deletes) them.

#Import necessary modules. boto3 is the AWS SDK for Python, and 
#datetime and parse are used for working with dates.

import boto3
import datetime
from dateutil.parser import parse

#Define a function days_old that calculates the number of days between the input date and the current date
def days_old(date):
parsed = parse(date).replace(tzinfo=None)
diff = datetime.datetime.now() - parsed
return diff.days

#Define the main Lambda function, which is the entry point for AWS Lambda.
def lambda_handler(event , context):
#Create an EC2 client using boto3.
ec2_client = boto3.client('ec2')

#Get a list of AWS regions using the EC2 client.
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]
for region in regions:
ec2 = boto3.client('ec2', region_name=region)
print("Region",region)

#Iterate through each region and create an EC2 client for that region.
amis = ec2.describe_images(Owners=['self']['Images'])

#Get a list of Amazon Machine Images (AMIs) owned by the account in the current region.
for ami in amis:
creationdate = ami['CreationDate']
age_days = days_old(creationdate)
image_id = ami['ImageId']
print("creation date {} days old {} imageId {}", creationdate, age_days, image_id )


#Iterate through each AMI, extract creation date, calculate age in days using the days_old function, and print relevant information.
if age_days >= 2:
print("Deleting imageId {}", image_id)

#If an AMI is more than or equal to 2 days old, print a message and deregister (delete) the AMI.
ec2.deregister_image(ImageId=image_id)

The script is designed to run as an AWS Lambda function, and it iterates through all regions, checks the age of AMIs, and deletes those that are older than or equal to 2 days. Note that the script assumes the Lambda function has the necessary permissions to describe and deregister EC2 images. Also, there’s a small correction in the describe_images line where ['self']['Images'] should be replaced with ['self'] to correctly fetch the AMIs owned by the account.

I hope you’ll find this helpful!
See you in the next chapter
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