[Step-by-Step] How to start & stop AWS EC2 automatically using Lambda & EventBridge
Tags: beginners, tutorial, aws
Published: 2023-07-03 16:21:43


## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fnlas0s2fto4iz8ljbp5.png)

Go to **Role**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/te35uk69689gymwx9aom.png)

Press **Create Role**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llbdfxh9wkru20ftgwqm.png)

Select **AWS Service** and **Lambda** and press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6uivd25l82ctpqf9svx.png)

Press **Create Policy**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bh2x9gwvcutj2xhaoas.png)

Press **JSON**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8prib2bmrc2oxy3sm1us.png)



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": "*"
    }
  ]
}
```
Go Back to **Visual** and Press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5o2mocym0ogfcpjehtm7.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnxhth063ls9ncpzumje.png)

Name the IAM Policy and Press **Create Policy**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nne5jg7rv7zmhnlp3q92.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t42mue7ios6dxwa094zv.png)

Select the created IAM Policy and Press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e52gg6ol6n05f6rfpie2.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9076e3tyd4fzur0pe7l.png)

Name the IAM Role and Press **Create Role**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uoiyq0cegpuzb46z7i9t.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98uauerhk19xidcfqx9a.png)
Now, you have created the IAM Role for Lambda

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtsmf1m2mbniuyt4i4qw.png)

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

Go to **Lambda**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu7ymytfe2gt1ewn7y6n.png)

Press **Create Function**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4447kqrgv8a5b7l4dw73.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llaikqv8lzf57gc4dyaj.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qgdcqf15yea9ywpnz2e2.png)

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))
```
Press **Deploy**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9i6bctc2kzzjvkpxjb7.png)
Now, you have created the lambda function for starting EC2
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6xx75yq5bgt0p0atdv8.png)

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))
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifnds559ve9oc38ufm6r.png)
### Step 3: Create 2 EventBridge Schedule to invoke 2 Lambda functions

Go to **EventBridge**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j72jnuwhisusla8zzf30.png)

Select **EventBridge Schedule** and Press **Create schedule**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/furgocxmlz3qoj8fkj7t.png)

Name the **EventBridge Schedule**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54gu8zbsbye9rdrerdbp.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75nugf0e367thd3ewmu4.png)

Select the **Timezone** and Press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23tqspevy1jiyruz68gn.png)

Select **Lambda**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snwijrudzy2k3mxrhulz.png)

Select the **Lambda Function** and Press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c7nna5yjbg0myje8xkrz.png)

Press **Next**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrnnmzusjrjkb84w1w2c.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m55jhqle1xqjn8zlh4n0.png)
Press **Create schedule**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2xhifl0bf4pg6e45j00.png)

Now, you have created the EventBridge Schedule for triggering lambda to start EC2
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pcdccfasiouqk2vkeiw.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdq4eang39fp38karool.png)

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.