Sitemap

Stop EC2 Instances During Public Holidays

3 min readMay 7, 2025

Reference: https://aws.amazon.com/blogs/mt/automate-suspension-of-an-aws-codepipeline-release-during-critical-events-using-aws-systems-manager-change-calendar-and-amazon-eventbridge/

Step 1: Go to AWS Systems Manager->Change Calendar and create a calendar

Step 2: Add Public holidays as events to this calendar.

Step 3: Launch an EC2 instance.

Step 4: Create a Python3.12 Lambda function which will start the instances the start if they are not running and stop the instances if they are already running. Use following code:

import boto3

# List your instance IDs here
INSTANCE_IDS = ['i-xyz']

def lambda_handler(event, context):
ec2 = boto3.client('ec2')

# Describe instance statuses
response = ec2.describe_instances(InstanceIds=INSTANCE_IDS)

instances_to_start = []
instances_to_stop = []

for reservation in response['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
state = instance['State']['Name']
print(f"Instance {instance_id} is in state {state}")

if state == 'stopped':
instances_to_start.append(instance_id)
elif state == 'running':
instances_to_stop.append(instance_id)

# Start instances
if instances_to_start:
print(f"Starting instances: {instances_to_start}")
ec2.start_instances(InstanceIds=instances_to_start)

# Stop instances
if instances_to_stop:
print(f"Stopping instances: {instances_to_stop}")
ec2.stop_instances(InstanceIds=instances_to_stop)

return {
'statusCode': 200,
'body': f"Started: {instances_to_start}, Stopped: {instances_to_stop}"
}

Grant following permissions to the Lambda’s IAM role.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:StartInstances",
"ec2:StopInstances"
],
"Resource": "*"
}
]
}

and set Timeout to 30 seconds.

Step 5: Create an Eventbridge rule with following pattern:

{
"source": ["aws.ssm"],
"detail-type": ["Calendar State Change"],
"resources": ["arn:aws:ssm:us-east-1:<AWS_ACCOUNT_ID>:document/SG_Public_Holiday"]
}

If you just want to perform any action at the start time of event, can use following event pattern.

{
"source": ["aws.ssm"],
"detail-type": ["Calendar State Change"],
"resources": ["arn:aws:ssm:us-east-1:<AWS_ACCOUNT_ID>:document/SG_Public_Holiday"],
"detail": {
"state": ["CLOSED"]
}
}

and set Lambda as target.

Step 6: To verify that setup is working fine, create a test event in your calendar.

and wait for the Eventbridge rule to be triggered at Calendar event’s start time. Once triggered, our EC2 instance will be stopped.

and when Eventbridge rule gets triggered at Calendar event’s stop time, our EC2 instance will be running again.

--

--

Vinayak Pandey
Vinayak Pandey

Written by Vinayak Pandey

Experienced Cloud Engineer with a knack of automation. Linkedin profile: https://www.linkedin.com/in/vinayakpandeyit/

Responses (1)