Skip to content

Instantly share code, notes, and snippets.

@serithemage
Last active June 1, 2021 01:13
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save serithemage/bb6ac8939a0819406ee27c9f34a55481 to your computer and use it in GitHub Desktop.
Save serithemage/bb6ac8939a0819406ee27c9f34a55481 to your computer and use it in GitHub Desktop.
Finds ec2 of all regions and stops instances where the tag AutoStopProtect is not set to True.
import boto3
import logging
# setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client = boto3.client('ec2')
runningInstanceFilter = [
{
'Name': 'instance-state-name',
'Values': ['running']
}
]
def lambda_handler(event, context):
instances = []
for region in client.describe_regions()['Regions']:
# define the connection
ec2 = boto3.resource('ec2', region_name=region['RegionName'])
# filter the running instances
instances = ec2.instances.filter(Filters=runningInstanceFilter)
for instance in instances:
shuttingDownFlag = True
for tags in instance.tags:
if tags["Key"] == 'AutoStopProtect' and tags["Value"] == 'True':
shuttingDownFlag = False
if shuttingDownFlag == True:
shuttingDown = instance.stop()
print(shuttingDown)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment