DEV Community

Lam Wing Chun
Lam Wing Chun

Posted on • Edited on

[Step-by-Step] How to start & stop AWS EC2 automatically using Lambda & EventBridge

Introduction

In this tutorial, we are going to automate starting and stopping EC2 via Lambda & EventBridge at regular intervals (e.g.running EC2 from 8:00 am to 8:00 pm). While the EC2 is stopped, we can save the compute cost during this time.

In order to let Lambda be able to start and stop the EC2 instance, we first need to assign the required IAM permission for lambda in Step1.

Once it is done, we can create two lambda functions, which the first one is for starting the EC2 and the second one is for stopping the EC2. After that, we can create the EventBridge Schedule to trigger the lambda function at the desired times.

Step Summary:

Step 1: Create IAM role for Lambda
Step 2: Create 2 Lambda function for starting and stopping EC2
Step 3: Create 2 EventBridge Schedule to invoke 2 Lambda functions

Step Details:

Step 1: Create IAM role for Lambda:

Go to IAM
Image description

Go to Role
Image description

Press Create Role
Image description

Select AWS Service and Lambda and press Next
Image description

Press Create Policy
Image description

Press JSON
Image description

Copy the following IAM Policy and paste in JSON Editor

{
  "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": "*"
    }, 
    {
      "Effect": "Allow",
      "Action": [
          "ses:SendEmail",
          "ses:SendRawEmail"
      ],
      "Resource": "*"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Go Back to Visual and Press Next
Image description
Image description

Name the IAM Policy and Press Create Policy
Image description
Image description

Select the created IAM Policy and Press Next
Image description
Image description

Name the IAM Role and Press Create Role
Image description

Image description
Now, you have created the IAM Role for Lambda

Image description

Step 2: Create 2 Lambda function for starting and stopping EC2

Go to Lambda

Image description

Press Create Function
Image description

Select Author from scratch and Name the Lamdba function
Select Python 3.9 runtime and Select IAM Role for Lambda
Press Create function
Image description

Image description

Modify the following Python Code and paste in Code source Editor

AutoStartEC2
Replace 'ap-east-1' to the designated Region for your situation
Replace 'i-0f7f94a56f47e7221' to the EC2 ID
you can add more instances in this array if you want
E.g. ['i-0f7f94a56f47e7221','i-0uweq7w7d7293','i-0wwq78e78we781']

import boto3
/////////////////////////////////////////////////////
region = 'ap-east-1'
instances = ['i-0f7f94a56f47e7221']
/////////////////////////////////////////////////////
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))
Enter fullscreen mode Exit fullscreen mode

Press Deploy
Image description
Now, you have created the lambda function for starting EC2
Image description

Repeat the above steps and refer to the following code to create the lambda function for stopping EC2

AutoStopEC2

import boto3
/////////////////////////////////////////////////////
region = 'ap-east-1'
instances = ['i-0f7f94a56f47e7221']
/////////////////////////////////////////////////////
ec2 = boto3.client('ec2', region_name=region)
def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))
Enter fullscreen mode Exit fullscreen mode

Image description

Step 3: Create 2 EventBridge Schedule to invoke 2 Lambda functions

Go to EventBridge
Image description

Select EventBridge Schedule and Press Create schedule

Image description

Name the EventBridge Schedule

Image description

Select Recurring schedule and Cron-based schedule

Define the cron expression for the schedule
cron(minutes hours day-of-month month day-of-week year)

For our cron expression, it will run at 8:00 am from Monday to Firday every week every year

Select Off in Flexible time window
Image description

Select the Timezone and Press Next
Image description

Select Lambda
Image description

Select the Lambda Function and Press Next
Image description

Press Next
Image description

Image description
Press Create schedule

Image description

Now, you have created the EventBridge Schedule for triggering lambda to start EC2
Image description

Repeat the above steps and Change the cron expression from 8 to 20 and select the AutoStopEC2 lambda function to create EventBridge Schedule for triggering lambda to stop EC2

Image description

Reference:
https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html?icmpid=docs_console_unmapped#cron-based
https://aws.amazon.com/lambda/pricing/?nc1=h_ls
https://repost.aws/knowledge-center/start-stop-lambda-eventbridge
https://www.amazonaws.cn/en/eventbridge/pricing/#:~:text=With%20Amazon%20EventBridge%2C%20you%20pay%20only%20for%20events,price%20is%20%C2%A5%206.75%20per%201%20million%20events.

Top comments (0)