Skip to content

Instantly share code, notes, and snippets.

@serithemage
Last active December 29, 2017 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serithemage/37cba1a8e2fdda14c619325bdd207513 to your computer and use it in GitHub Desktop.
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
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