Automating EC2 with AWS Lambda Using Boto3- Lab 2

Shivani Singh
1 min readNov 27, 2023

Problem Statement:

Develop an AWS Lambda function for managing the state of Amazon EC2 instances across all available AWS regions. The function should iterate through each region, identify running EC2 instances, and stop them to optimize resource usage during non-operational periods.


#Import the Boto3 library, which is the official Amazon Web Services
#(AWS) SDK for Python

import boto3

#Define the Lambda function handler. In AWS Lambda, this is the entry point
#for the execution of the function

def lambda_handler(event, context):
#Create an EC2 client using Boto3. The ec2_client object is an
#instance of the EC2 service client, which can be used to make API calls to EC2.
ec2_client = boto3.client('ec2')

# Use the describe_regions method of the EC2 client to
# get information about all AWS regions.
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]

# Iterate over each region
for region in regions:
ec2 = boto3.resource('ec2', region_name=region)
print("Region:", region)

# Get only running instances
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

#Use the stop method on each instance to stop it
for instance in instances:
instance.stop()
print("Stopped Instance:", instance.id)

Note: The solution aims to automate the management of EC2 instances across all regions, promoting efficiency and cost savings. It is crucial to carefully test and validate the function in a controlled environment before deploying it to production, as stopping instances may impact services relying on those instances.

Hope this was helpful
See you in 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