Skip to content

Update lambda_function.py #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions EC2/Stopping-EC2-Instances-Nightly/lambda_function.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
import boto3
import boto3 #library used to create ec2_client object to interact with EC2 INSTANCES INSIDE OF AWS


def lambda_handler(event, context):

# Get list of regions
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
# retrieves a list of available AWS regions by calling ec2_client.describe_regions(). The response is a dictionary containing information about the regions. The code extracts the region names and stores them inside of the regions list
for region in ec2_client.describe_regions()['Regions']]

# Iterate over each region
for region in regions:
#creates an EC2 resource object (ec2) for the current region using boto3.resource('ec2', region_name=region).
ec2 = boto3.resource('ec2', region_name=region)

#prints the current region to the console
print("Region:", region)

# Get only running instances
#code filters the EC2 instances in the current region to get only the running instances.
#It uses ec2.instances.filter() and specifies a filter to include instances with the state 'running'
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name',
'Values': ['running']}])

# Stop the instances
for instance in instances:
instance.stop()
#prints the id of each stopped instance
print('Stopped instance: ', instance.id)