Stop and start EC2 instances on a schedule with Lambda and EventBridge Scheduler
A dev box used 50 hours a week but running all 168 costs more than twice what it needs to. Here's a small, least-privilege setup that stops tagged EC2 instances in the evening and starts them in the morning, and the problems you'll want to handle before relying on it.
What you'll build
- A tag on each instance you want scheduled:
schedule=office-hours. - One Lambda function that starts or stops every instance with that tag.
- Two EventBridge Scheduler schedules, in your own time zone, that call it with
startorstop.
1. Tag the instances
Add schedule=office-hours to each instance in the EC2 console, or use Tag Editor for many at once. The function only touches tagged instances, and the IAM policy below enforces that too.
2. Create the function's role
Attach AWSLambdaBasicExecutionRole for logs, plus this policy. Starting and stopping is only allowed on instances that carry the tag.
{
"Version": "2012-10-17",
"Statement": [
{ "Effect": "Allow", "Action": "ec2:DescribeInstances", "Resource": "*" },
{ "Effect": "Allow",
"Action": ["ec2:StartInstances", "ec2:StopInstances"],
"Resource": "arn:aws:ec2:*:*:instance/*",
"Condition": { "StringEquals": { "aws:ResourceTag/schedule": "office-hours" } } }
]
}
3. Write the function
Python 3, in the same region as the instances. It handles instances one at a time, so one instance that fails to start (for example, with insufficient capacity) doesn't stop the rest. It raises an error at the end if anything failed, so Lambda's error metric shows it.
import boto3
ec2 = boto3.client("ec2")
def handler(event, context):
action = event["action"] # "start" or "stop"
from_state = "stopped" if action == "start" else "running"
ids = []
pages = ec2.get_paginator("describe_instances").paginate(Filters=[
{"Name": "tag:schedule", "Values": ["office-hours"]},
{"Name": "instance-state-name", "Values": [from_state]},
])
for page in pages:
for reservation in page["Reservations"]:
ids += [i["InstanceId"] for i in reservation["Instances"]]
call = ec2.start_instances if action == "start" else ec2.stop_instances
failed = {}
for instance_id in ids:
try:
call(InstanceIds=[instance_id])
except Exception as error:
failed[instance_id] = str(error)
print({"action": action, "instances": ids, "failed": failed})
if failed:
raise RuntimeError(f"{len(failed)} instance(s) failed to {action}: {failed}")
4. Schedule it in your time zone
Use EventBridge Scheduler rather than the older EventBridge rules. Scheduler takes a time zone and adjusts for daylight saving; rules run in UTC only. Scheduler needs a role it can assume with lambda:InvokeFunction on the function.
aws scheduler create-schedule --name ec2-office-start \
--schedule-expression "cron(0 8 ? * MON-FRI *)" \
--schedule-expression-timezone America/New_York \
--flexible-time-window Mode=OFF \
--target '{"Arn":"FUNCTION_ARN","RoleArn":"SCHEDULER_ROLE_ARN","Input":"{\"action\":\"start\"}"}'
aws scheduler create-schedule --name ec2-office-stop \
--schedule-expression "cron(0 19 ? * MON-FRI *)" \
--schedule-expression-timezone America/New_York \
--flexible-time-window Mode=OFF \
--target '{"Arn":"FUNCTION_ARN","RoleArn":"SCHEDULER_ROLE_ARN","Input":"{\"action\":\"stop\"}"}'
That's it for fixed hours: about 50 hours on and 118 off each week.
The gotchas
Encrypted volumes won't start
If an instance's EBS volumes use a customer-managed KMS key, starting it needs kms:CreateGrant on that key. Without it, the start call succeeds and the instance goes straight back to stopped. Add the permission for each key to the function's role.
Failures are silent unless you look
Create a CloudWatch alarm on the function's Errors metric and send it to an SNS topic you read. Otherwise a capacity error at 8 a.m. becomes a developer's ticket at 9.
Tags drift
Someone renames the tag, or launches a new instance without it, and it quietly drops out of the schedule. It's worth a weekly check for running instances without a schedule tag.
People need machines outside the schedule
This is the big one. Someone needs a box at 9 p.m., or on Saturday, or for an hour on a day it's usually off. With this setup they need AWS console access, or someone who has it. Teams often add a second function behind a URL that starts an instance, then have to decide when it stops again. Usually the answer is "at the next scheduled stop", so a one-hour need becomes an all-night cost.
RDS is different
Databases need rds:StartDBInstance and rds:StopDBInstance, take several minutes to become available, should start before the app servers that use them, and restart themselves after seven days stopped. See How to keep an RDS database stopped for more than 7 days.
Is it worth it? For a few small instances, maybe not: a t3.micro left on all month costs under $10. The savings add up with larger dev and test boxes and databases. Count the engineering time to build, alarm and maintain this alongside the saving.