Stop / Start EC2 Instance on a schedule
From Cramsession
✍️ Verified Author: Mflavell • Click to view professional profile & credentials
Introduction
This approach depends on three components.
- AWS IAM for rights
- Lambda to execute the code
- Event bridge to execute the lambda code
Setup rights
Create a policy
- Launch the IAM Console
- Click Policies
- Click Creare policy
- Select JSON (Blue button, top right)
- edit the section and paste the following between the square brackets in the statement.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
}
]
}
- Name the polcy EC2_StartStop
Create a role
- In IAM, Click Roles.
- Select AWS Service
- Select Lambda from the dropdown
- Select Next
- Search for and select EC2_StsartStop
- Name the policy Lambda_StartStop
Add Lambda functions
Create Start Function
Note down the instance ID and region for the EC2 instance.
- Name the function startEC2
- Select Python 3.13 for runtime.
- Change default execution role
- Select Ues existing role
- Select Lambda_StartStop
- Select create function
Paste the following code:
replace rrrrr wih the region name replace iiiiii with the instance ID
import boto3
region = 'rrrrrrr'
instances = ['iiiiiii']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
- Save the function
Create Stop Function
Note down the instance ID and region for the EC2 instance.
- Name the function stopEC2
- Select Python 3.13 for runtime.
- Change default execution role
- Select Ues existing role
- Select Lambda_StartStop
- Select create function
Paste the following code:
replace rrrrr wih the region name replace iiiiii with the instance ID
import boto3
region = 'rrrrrrr'
instances = ['iiiiiiiiiii']
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
- Save the function