Last active
May 1, 2021 03:35
-
-
Save gcagle3/4498797cc3ae46a84cf8dd6dca9b288a to your computer and use it in GitHub Desktop.
Boto3 Python Script to Stop Instances Unless Tagged "KEEP:KEEP"
This file contains 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 | |
# 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