EC2 Start and Stop using Lambda Function and Eventbridge

EC2 Start and Stop using Lambda Function and Eventbridge

with code and IAM role

We can schedule the aws instance to stop and start with the help of lambda function by following steps:-

Step 1 :-

Make a custom role in IAM and attach the following custom policy:-

policy:-

{
    "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": "*"
        }
    ]
}

Step 2:- Make sure you have elastic IP attached in case your server is in public.

Step 3:- Create a new function with a name (your choice).

Select the runtime as python 3.9

Step4:- In the permission section select the custom role which you have made:-

Create function

Step5:-

In the code section shown in the picture:

use the below code for starting the ec2-instance

import boto3

def lambda_handler(event, context):
    # Start the instance
    ec2_client = boto3.client('ec2')
    response = ec2_client.start_instances(
        InstanceIds=[
            'i-00c5b6e1657dd6733', 'i-0aaad7b89f3efb200', 'i-016bb64a7f55c926f'
        ]
    )

Step6:- then add the trigger as shown in the picture:-

in the trigger section chose Eventbridge as shown in the picture.

after the make a new rule and choosing your schedule expression in Cron

eg of cron:- cron(5,35 14 ? *)

your and chose cron as per your need.

Step 7:- Configure another lambda function same as the ec2 start lambda function for ec2 stop.

all the steps are the same just code is different

use the below code for stopping the ec2-instance

import boto3


def lambda_handler(event, context):
    # Stop the instance
    ec2_client = boto3.client('ec2')
    response = ec2_client.stop_instances(
        InstanceIds=[
            'i-00c5b6e1657dd6733','i-0aaad7b89f3efb200','i-016bb64a7f55c926f'
        ]
    )