Skip to content

Instantly share code, notes, and snippets.

@gcagle3
Last active May 1, 2021 03:35
Show Gist options
  • Save gcagle3/4498797cc3ae46a84cf8dd6dca9b288a to your computer and use it in GitHub Desktop.
Save gcagle3/4498797cc3ae46a84cf8dd6dca9b288a to your computer and use it in GitHub Desktop.
Boto3 Python Script to Stop Instances Unless Tagged "KEEP:KEEP"
import boto3
# 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 only running instances
instances = ec2.instances.filter()
reserved_instances = ec2.instances.filter(Filters=[{'Name': 'tag:KEEP','Values': ['KEEP']}])
# # Stop the instances
for instance in instances:
if instance not in reserved_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