Skip to content

Instantly share code, notes, and snippets.

@gcagle3
Created May 1, 2021 03:32
Show Gist options
  • Save gcagle3/9af8ac2ba825959f9036ec43bcb09317 to your computer and use it in GitHub Desktop.
Save gcagle3/9af8ac2ba825959f9036ec43bcb09317 to your computer and use it in GitHub Desktop.
AWS - Simple Lambda (python/boto3) function to stop EC2 instances
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