# EC2 Start and Stop using Lambda Function and Eventbridge

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:-

```plaintext
{
    "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 <mark>python 3.9</mark>

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1684019400924/938c139c-a1ff-41b6-bb8b-fa15bb668815.png align="center")

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1684019712420/45a0322a-4bed-45e0-84de-df3cb6ace149.png align="center")

<mark>Create function</mark>

Step5:-

In the code section shown in the picture:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1684019820691/f7903244-0db0-43b4-9d87-4be20abcf666.png align="center")

use the below <mark>code</mark> for starting the ec2-instance

```plaintext
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:-

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1684019982655/52f33c55-8eb3-476a-9618-6568cbc9a5ee.png align="center")

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.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1684020200948/208183b7-c643-4bf4-92c5-1a7e5bfcf492.png align="center")

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

```plaintext
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'
        ]
    )
```
