Created
May 1, 2021 03:32
-
-
Save gcagle3/9af8ac2ba825959f9036ec43bcb09317 to your computer and use it in GitHub Desktop.
AWS - Simple Lambda (python/boto3) function to stop EC2 instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def lambda_handler(event, context): | |
# Get list of regions | |
ec2_client = boto3.client('ec2') | |
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 all instances with status "running" | |
instances = ec2.instances.filter( | |
Filters=[{'Name': 'instance-state-name', | |
'Values': ['running']}]) | |
# Stop running instances | |
for instance in instances: | |
instance.stop() | |
print('Stopped instance: ', instance.id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment