Last active
June 1, 2021 01:13
-
-
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.
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 | |
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