mda590
2/7/2017 - 7:39 PM

Example EC2 Scheduler Script based on a tag value

Example EC2 Scheduler Script based on a tag value

import boto3
from datetime import datetime, timedelta

def lambda_handler(event, context):
    try:
        # Create connection to the EC2 using Boto3 resources interface
        ec2 = boto3.resource('ec2', region_name='us-east-1')

        # Get the current time
        timeOffset = datetime.utcnow() + timedelta(hours=defaultTimeZone)
        now = timeOffset.strftime("%H%M")
        nowDay = timeOffset.strftime("%a").lower()

        # Set default values, instantiate lists
        startList = []
        stopList = []
        customTagName = "ec2-schedule"

        # List all instances
        instances = ec2.instances.all()

        print "Creating", awsregion, "instance lists..."

        # For all instances
        for i in instances:
            # Instance must have tags to be able to be scheduled
            if i.tags != None:
                # For each tag
                for t in i.tags:
                    # Check that the tag key equals the custom tag name
                    if t['Key'] == customTagName:

                        state = i.state['Name']
                        timezone = -6

                        # Split the tag into repsective parts
                        ptag = t['Value'].split(";")
                        
                        # Get timing values from tag Value
                        if len(ptag) >= 1:
                            startTime = ptag[0]
                            stopTime = ptag[1]
                            daysActive = ptag[2].lower()

                        isActiveDay = False

                        # Days of Week
                        if daysActive == "all":
                            isActiveDay = True
                        elif daysActive == "weekdays":
                            weekdays = ['mon', 'tue', 'wed', 'thu', 'fri']
                            if (nowDay in weekdays):
                                isActiveDay = True
                        else:
                            daysActive = daysActive.split(",")
                            for d in daysActive:
                                if d.lower() == nowDay:
                                    isActiveDay = True

                        # Append to start list
                        if startTime <= str(now) and str(now) <= stopTime and \
                                isActiveDay == True and state == "stopped":
                            startList.append(i.instance_id)
                            print i.instance_id, " added to START list"

                        # Append to stop list
                        if (startTime >= str(now) or stopTime <= str(now)) and \
                                isActiveDay == True and state == "running":
                            stopList.append(i.instance_id)
                            print i.instance_id, " added to STOP list"

        # Execute Start and Stop Commands
        if startList:
            print "Starting", len(startList), "instances", startList
            ec2.instances.filter(InstanceIds=startList).start()
        else:
            print "No Instances to Start"

        if stopList:
            print "Stopping", len(stopList) ,"instances", stopList
            ec2.instances.filter(InstanceIds=stopList).stop()
        else:
            print "No Instances to Stop"

    except Exception as e:
        print ("Exception: "+str(e))