diff --git a/EC2/Stopping-EC2-Instances-Nightly/lambda_function.py b/EC2/Stopping-EC2-Instances-Nightly/lambda_function.py index 9e41b17..43bbb27 100644 --- a/EC2/Stopping-EC2-Instances-Nightly/lambda_function.py +++ b/EC2/Stopping-EC2-Instances-Nightly/lambda_function.py @@ -1,4 +1,4 @@ -import boto3 +import boto3 #library used to create ec2_client object to interact with EC2 INSTANCES INSIDE OF AWS def lambda_handler(event, context): @@ -6,15 +6,18 @@ 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']}]) @@ -22,4 +25,5 @@ def lambda_handler(event, context): # Stop the instances for instance in instances: instance.stop() + #prints the id of each stopped instance print('Stopped instance: ', instance.id)