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/