4.04.2017

How to Automatically Shutdown Expensive Development Resources on AWS

Put this into a Lambda function and activate it using CloudWatch, and any EC2s with a tag of AutoShutdown: "true" will be shutdown when this is run!


import boto3
region = 'us-east-1'

ec2 = boto3.resource('ec2', region_name=region)

filters = [
    {
      'Name': 'tag:AutoShutdown',
      'Values': ['true']
    }
]

def getInstanceName(instance):
    for tag in instance.tags:
        if tag["Key"] == "Name":
            return tag["Value"]

def lambda_handler(event, context):
    for instance in ec2.instances.filter(Filters=filters):
        instance.stop()
        print getInstanceName(instance)  + " stopped"