Skip to content

Instantly share code, notes, and snippets.

@denzhel
Last active April 22, 2021 09:01
Show Gist options
  • Select an option

  • Save denzhel/11d8f5ec83858f26723b6b1e98e33190 to your computer and use it in GitHub Desktop.

Select an option

Save denzhel/11d8f5ec83858f26723b6b1e98e33190 to your computer and use it in GitHub Desktop.
scheduled_ec2_shutdown

To schedule the shutdown and startup of your EC2 instances, you can use this Lambda Python code. Please note that this code looks for EC2 instance by their Tag(line 8), e.g role = runner.

import boto3

# Define variables
client = boto3.client('ec2', region_name="us-east-1")
filters =[ { 'Name': 'tag:<KeyName>', 'Values': ['<ValueName>'] } ]

# Get the list of instances by searching for the tag configured above
instances_list= []
response = client.describe_instances(Filters=filters)
for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        instances_list.append(instance["InstanceId"])


def lambda_handler(event, context):
    # Check if a parameter was given and act accordingly
    if event["action"].lower() == "start":
        print(f"Starting the following instances: {instances_list}")
        client.start_instances(InstanceIds=instances_list)
    elif event["action"].lower() == "stop":
        print(f"Stopping the following instances: {instances_list}")
        client.stop_instances(InstanceIds=instances_list)
    else:
        return "action not recognized"
    

Use this guide to setup the rest of the components(IAM Roles, IAM Policy and CloudWatch triggers): https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment