Automating EC2 with AWS Lambda Using Boto3- Lab 2
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