Stop Non-Production EC2 Instances Out of Hours With a Tag-Driven Lambda and EventBridge Scheduler
Use the AWS EC2 documentation's Lambda and schedule approach to stop tagged test instances at night, with a dry run, a scoped role and a rollback.

Advertising disclosure: this article includes partner links. KBY may earn a commission if you sign up or buy through one, at no extra cost to you. How we make money.
Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.
The AWS EC2 documentation lists AWS Lambda with an EventBridge rule as one supported way to stop and start instances on a schedule. That is a sound basis for trimming the cost of development and test servers that nobody uses overnight. It leaves the awkward parts to you: which instances to touch, who may touch them, and what happens when a run fails.
A small Lambda function, driven by EventBridge Scheduler, can stop tagged instances in the evening and start them in the morning. It ships in dry-run mode, and it acts only after a pilot proves it picks the right machines. Work in a test account or a test Region first, because a stop request is easy to send and a surprised team is hard to apologise to.
The same documentation also names Instance Scheduler on AWS, which Amazon notes carries additional charges. Choose it if you want a packaged product. Choose the function below if you would rather own a few dozen lines that you can read in one sitting.
#How it usually goes when stops depend on memory
Most teams start with memory. Someone stops the development instances from the console on Friday afternoon, using Instance state, then Stop instance, or runs aws ec2 stop-instances --instance-ids with a list they keep in a note. It works until that person is on leave. Nothing records the intent, so a forgotten instance looks like any other running one.
The next step is a script on an administrator’s laptop or a long-running utility instance. That moves the risk rather than removing it, because the script needs credentials that can stop anything, and it stops running when its host does. AWS recommends stopping through the console, CLI or API rather than the operating system, since EC2 then makes a hard shutdown if the guest does not stop cleanly, and CloudTrail records the API call.
Three documented facts shape every design here. First, only instances with an EBS root volume can be stopped, and an instance-store root cannot. Second, stopping erases data on instance store volumes. Third, a started instance is typically migrated to a new host and given a new public IPv4 address, so anything that depends on the old address will break.
#A better way: one tag, one function, two schedules
The design has one tag, one function and two schedules. Instances opt in with a tag such as OutOfHours=true. A single Lambda function takes an action of stop or start, finds the matching instances by tag and state, and sends one request for the lot. EventBridge Scheduler calls it at 19:00 and 07:00 on weekdays, in the London time zone.
Compared with the manual method above, the decision moves into a tag and the action moves into a role that can do little else. The tag keeps intent on the instance, where its owner can see it. Removing the tag takes an instance out of the schedule without anyone editing code. The function also filters on instance state, so a stop request never goes to an instance that is already stopped.
Why use Lambda at all? EventBridge Scheduler has universal targets that can call an AWS API directly, so a direct call to the EC2 stop action needs no code. The catch is that Scheduler does not support read-only actions whose names begin with prefixes such as describe. It therefore cannot look instances up by tag, so you would have to put fixed instance IDs in the schedule. If your list never changes, that is the simpler route.
The time zone matters more than it looks. A cron schedule is evaluated in UTC or in a time zone you name, and Scheduler adjusts for daylight saving time in that zone. When the clocks go forward, an invocation that falls on a time that does not exist is skipped. Evening and early-morning times stay clear of the changeover, but keep the rule in mind for anything scheduled in the hour the clocks change.
#Setting it up step by step
Build in a test account and keep the pilot small. Two tagged instances and one untagged control instance are enough to prove the whole path, and the control shows what happens to a machine that should be left alone.
- Launch or choose two EBS-backed test instances and tag both
OutOfHours=true. Leave a third without the tag. Confirm the lookup the function will use:aws ec2 describe-instances --filters "Name=tag:OutOfHours,Values=true" "Name=instance-state-name,Values=running" --query "Reservations[].Instances[].InstanceId" --output textshould print exactly the two tagged instance IDs. - Create the function’s execution role with Lambda as the trusted service, using a trust policy that names
lambda.amazonaws.comand the actionsts:AssumeRole. Then attach theAWSLambdaBasicExecutionRolemanaged policy, which lets the function write its logs to CloudWatch Logs. - Add an inline policy to that role. Describing instances does not support resource-level permissions, so it needs
*. Stop and start can be limited to instances in one account and Region, and to the tag, as shown in the policy below. - Create the function in the Lambda console, choose a current Python runtime from the supported list, and choose the role you made under Permissions with Use another role. Paste in the code below. Set the environment variable
DRY_RUNtotrue. - Raise the timeout. The default is 3 seconds, which is too tight for a lookup followed by a stop request. In the console, open Configuration, then General configuration, then Edit, or run
aws lambda update-function-configuration --function-name ec2-out-of-hours --timeout 60. - Create a second role for EventBridge Scheduler. Trust
scheduler.amazonaws.comand allowlambda:InvokeFunctionon this one function. The documentation’s example allows every function, so narrow it to the function’s ARN. - Create an Amazon SQS standard queue to act as the schedule’s dead-letter queue, and allow the Scheduler role to send messages to it. A FIFO queue is not supported for this purpose.
- Create the two schedules in the disabled state, so nothing fires until the pilot passes, with the commands further down.
Following along? Tap a step’s number to tick it off.
The inline policy gives the function exactly what the code uses. The tag condition follows the pattern in the EC2 documentation’s policy examples, which apply aws:ResourceTag to other actions. Treat it as a backstop to prove in the pilot. The code filter is the primary control, and the validation section checks the condition in both directions.
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Action": "ec2:DescribeInstances",
7 "Resource": "*"
8 },
9 {
10 "Effect": "Allow",
11 "Action": ["ec2:StopInstances", "ec2:StartInstances"],
12 "Resource": "arn:aws:ec2:REGION:ACCOUNT_ID:instance/*",
13 "Condition": {
14 "StringEquals": { "aws:ResourceTag/OutOfHours": "true" }
15 }
16 }
17 ]
18}The function itself is short. It reads the action from the event, finds instances in the right starting state with the tag and an EBS root, and sends one request. The EC2 DryRun parameter does the checking in dry-run mode, because EC2 answers DryRunOperation when the role has permission and UnauthorizedOperation when it does not. That makes the dry run a real permission test, not just a log line.
1import logging
2import os
3
4import boto3
5from botocore.exceptions import ClientError
6
7ec2 = boto3.client("ec2")
8logger = logging.getLogger()
9logger.setLevel("INFO")
10
11TAG_KEY = os.environ.get("TAG_KEY", "OutOfHours")
12TAG_VALUE = os.environ.get("TAG_VALUE", "true")
13DRY_RUN = os.environ.get("DRY_RUN", "true").lower() != "false"
14FROM_STATE = {"stop": "running", "start": "stopped"}
15
16
17def find_instances(state):
18 filters = [
19 {"Name": "tag:" + TAG_KEY, "Values": [TAG_VALUE]},
20 {"Name": "instance-state-name", "Values": [state]},
21 {"Name": "root-device-type", "Values": ["ebs"]},
22 ]
23 ids, token = [], None
24 while True:
25 args = {"Filters": filters}
26 if token:
27 args["NextToken"] = token
28 page = ec2.describe_instances(**args)
29 for reservation in page["Reservations"]:
30 ids.extend(i["InstanceId"] for i in reservation["Instances"])
31 token = page.get("NextToken")
32 if not token:
33 return ids
34
35
36def lambda_handler(event, context):
37 action = event.get("action")
38 if action not in FROM_STATE:
39 raise ValueError("action must be stop or start")
40 ids = find_instances(FROM_STATE[action])
41 logger.info("action=%s dry_run=%s matched=%s", action, DRY_RUN, ids)
42 if not ids:
43 return {"action": action, "matched": 0}
44 call = ec2.stop_instances if action == "stop" else ec2.start_instances
45 try:
46 call(InstanceIds=ids, DryRun=DRY_RUN)
47 except ClientError as err:
48 if err.response["Error"]["Code"] != "DryRunOperation":
49 raise
50 logger.info("dry run passed for %s", ids)
51 return {"action": action, "matched": len(ids), "dry_run": True}
52 logger.info("requested %s for %s", action, ids)
53 return {"action": action, "matched": len(ids), "dry_run": False}Create the schedules last. Each one calls the function with a small JSON input, evaluates its cron expression in the London zone, and sends failed invocations to the dead-letter queue. Create the start schedule the same way, with cron(0 7 ? * MON-FRI *) and the input {"action":"start"}.
1aws scheduler create-schedule --name ec2-out-of-hours-stop \
2 --schedule-expression 'cron(0 19 ? * MON-FRI *)' \
3 --schedule-expression-timezone "Europe/London" \
4 --state DISABLED \
5 --flexible-time-window '{"Mode":"OFF"}' \
6 --target '{"Arn":"FUNCTION_ARN","RoleArn":"SCHEDULER_ROLE_ARN","Input":"{\"action\":\"stop\"}","DeadLetterConfig":{"Arn":"DLQ_ARN"}}'
#Keeping it safe: who can stop what
Because the tag decides which machines are stopped, whoever can edit tags can influence what the function stops. Limit tag changes on production instances to the people who already manage them, and review the tag with the same care as a security group rule. A production database that picks up the tag by copy-and-paste will be stopped at 19:00.
The role is the second guardrail. Its stop and start permissions are limited to one account and Region, and the tag condition narrows them further. The function also filters on an EBS root volume, so it never asks EC2 to stop an instance-store machine, which EC2 cannot stop. Keep the function in one Region on purpose, since the lookup only sees instances in the Region where it runs.
Leave the stop options at their defaults. The default stop attempts a graceful operating system shutdown. The Force and skipOsShutdown parameters exist, but AWS warns that skipping the graceful shutdown can lose or corrupt data, and that a forced stop means you must run file system checks afterwards. A scheduled job should never reach for them.
Instances in an Auto Scaling group are outside this playbook. The EC2 documentation notes that Auto Scaling terminates unneeded instances rather than stopping them, so a schedule that stops group members can conflict with the group’s own scaling. Remove the tag from group members, and use the group’s own scaling settings instead.
#Verify it on the pilot before you enable anything
Work through these checks in order, and stop at the first one that does not behave as described. Each check has a pass condition, so you never have to judge a result by feel.
- Invoke the function in dry-run mode with
aws lambda invoke --function-name ec2-out-of-hours --cli-binary-format raw-in-base64-out --payload '{"action":"stop"}' response.json. Pass: the function logs the two tagged instance IDs, reports a dry run, and no instance changes state. - Read the log group
/aws/lambda/ec2-out-of-hours. Logs can take 5 to 10 minutes to appear. Pass: the matched list holds the tagged instances and does not hold the control. - Prove the guardrail on the control instance. Using credentials for a test role that carries the same inline policy, run
aws ec2 stop-instances --instance-ids CONTROL_ID --dry-run. Pass: the answer isUnauthorizedOperation. ADryRunOperationanswer means the tag condition is not limiting the role, and you must fix the policy before going further. - Set
DRY_RUNtofalseand invoke the stop action. Pass: the two tagged instances move to stopped, the control stays running, and CloudTrail shows a StopInstances event for the function’s role. - Invoke the start action. Pass: both instances return to running. Note the public IPv4 address before and after, because it will probably have changed.
- Enable the two schedules for one working day. Pass: the stop and start both fire on time, the dead-letter queue stays empty, and the log shows one run for each.
#What goes wrong in practice
The most common failure is the default timeout. The function is set to 3 seconds, the lookup and the stop request take longer, and every run ends in a timeout with the instances still running. Raise the timeout before the first real run, and check that the log shows the final message, not only the first.
The second is a mismatch between where the function runs and where the instances live. The function only sees one Region. A tagged instance in another Region is never stopped, and no error says so. List the Regions that hold tagged instances, and deploy one copy of the function in each.
The third is data that vanishes. If an instance holds anything on instance store volumes, the stop erases it, and an instance whose root is an instance store cannot be stopped at all. Check the volumes of every candidate before tagging it. Anything holding a long-running job, a build or a database should be left out of the schedule.
Last, plan for the morning. Start requests are cheap, but a new public IPv4 address can break an allow-list or a DNS record that points at the old one. Anyone connecting to a test server by its public address needs to know that, and the right fix is a name that follows the instance, not a longer list of exceptions.

#Backing out safely
Setting DRY_RUN to true is the fastest rollback, because the function then makes no change at all. It needs no schedule edit and takes effect on the next invocation. Do that first when anything looks wrong. Then disable or delete the two schedules so nothing fires while you investigate. The command aws scheduler delete-schedule --name ec2-out-of-hours-stop removes one.
If instances were stopped that should not have been, start them with aws ec2 start-instances --instance-ids ID or from the console. Stopped instances keep their root and data volumes, so nothing is lost beyond instance store data. If one is stuck in the stopping state, follow the EC2 troubleshooting page before using Force, because a forced stop needs a file system check afterwards.
Finally, remove the tag from anything that should leave the schedule. Keep the function and role until the review is done, because the logs and the role’s policy are the evidence of what the job was allowed to do.
#What to track after the roll-out
Start with one number: how many tagged instances are running at 20:00 on a weekday. It should be zero. Check it with the same describe command used in the pilot, and treat any other result as a failed run to investigate. A similar check at 07:15 should find every tagged instance running.
The stopped share of the week is easy to work out and hard to dispute. A 19:00 to 07:00 window on weekdays, plus the whole weekend, leaves a tagged instance stopped for 108 of the 168 hours in a week, about 64 per cent. Only instance usage stops billing. AWS states that EBS volumes remain and keep being charged, and that each start is charged for a minimum of one minute.
Review three more signals each month: the dead-letter queue depth, any Lambda errors in the log group, and the list of tagged instances against the list of owners. An instance whose owner has left is the usual source of a surprise.
#The AWS EC2 documentation pages this relies on
Keep these open while you build, because they settle the questions that tend to come up. Check each one for changes when you review the job, since stop and start behaviour is exactly the kind of detail that gets refined over time.
- Stop and start Amazon EC2 instances, in the EC2 User Guide, for what a stop does, the new public address, and the automatic options.
- StopInstances and StartInstances in the EC2 API Reference, for the
DryRun,ForceandskipOsShutdownparameters and the billing notes. - DescribeInstances in the same reference, for the
tag:andinstance-state-namefilters, and for pagination withNextToken. - IAM policy examples for Amazon EC2, for the pattern that scopes stop and start to named instances and uses resource tags.
- Schedule types and universal targets in the EventBridge Scheduler User Guide, for cron syntax, time zones and daylight saving behaviour.
#Before you roll it out
- The pilot ran in a test account or Region, with a tagged pair and an untagged control, and every check passed.
- The function’s timeout is raised above the 3 second default, and
DRY_RUNwas switched on and off deliberately. - The execution role has describe on all resources and stop and start only for one account, one Region and the tag.
- The dry-run check on the control instance returned
UnauthorizedOperation. - Both schedules name the London time zone, point at a standard SQS dead-letter queue, and were enabled only after the pilot.
- Every tagged instance has an EBS root, no data on instance store volumes, and an owner who knows the new-address behaviour.
- Nothing in an Auto Scaling group carries the tag, and production instances are not tagged by copy-and-paste.
- Someone owns the monthly review, and the rollback steps are written down where the on-call engineer will find them.
About this page
Credited to
Dates
Published
Sources
Corrections
No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.
Found this useful? Follow KBY for more like it.
Recommended reading
More from KBY that goes with this article.

Small business ITBackups a small business can actually restore from: three copies, one offline, and a test
5 min read

Related articles
Application Lifecycle
Uninstall a pkg-Installed Mac App Completely Using Its pkgutil Receipt
No uninstall for a Mac .pkg? Read its pkgutil receipt, stop launchd services, move the app's files to a holding folder and forget the receipt, with rollback.
ReadApplication Lifecycle
Check a Mac App or pkg Is Developer ID Signed and Notarized Before You Deploy It
Run codesign, spctl, pkgutil and stapler on a test Mac to confirm an app or pkg is signed and notarized, and find pkgs that stop installing in 2027.
ReadEnterprise IT Management
Detect Microsoft 365 Configuration Drift with Tenant Configuration Management: Snapshot, Baseline and Monitor
Snapshot approved Microsoft 365 settings, monitor them against that baseline every six hours, and read each drift through Microsoft Graph.
ReadSecurity
NCSC Says AI Has Taken a Step Change in Offensive Cyber Capability
AISI says two AI models solved its hardest hacking range with no planted flaw. The NCSC wants IT teams to shrink internet exposure and patch in hours.
ReadDiscover more
Graduate Learning
- TutorialHow AWS Decides Allow or Deny: IAM Policy Evaluation Step by Step
- TutorialRecovering a Deleted Amazon S3 Object from a Versioned Bucket
- TutorialCopying SharePoint Online Document Libraries to Amazon S3 with Amazon AppFlow
- TutorialIncreasing an AWS EBS Volume Size and Extending the Linux File System
Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
Operate smarter, with fewer recurring tickets.
Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.
Comments
Add a thoughtful note on Stop Non-Production EC2 Instances Out of Hours With a Tag-Driven Lambda and EventBridge Scheduler. Comments are checked for spam and held for moderation before appearing.