Last active
December 29, 2017 06:27
-
-
Save serithemage/37cba1a8e2fdda14c619325bdd207513 to your computer and use it in GitHub Desktop.
An AWS Lambda function that stops all instances that are not protect tagged
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 | |
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: | |
# Stop Protect Key name is AutoStopProtect. Only 'True' is valid. | |
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