Stop and Start EC2 instances at predefined times Using Lambda and EventBridge - STOPINATOR 2.0
Tags: webdev, python, productivity, devops
Published: 2022-02-12 10:19:14


## DAY 7 - Stop and Start EC2 instances at predefined times Using Lambda and EventBridge  - STOPINATOR 2.0  
☁️[100 days of Cloud- **Day Seven**](https://github.com/anuvindhs/100daysofcloud)
 ✅[Follow Me on Twitter](https://twitter.com/anuvindhs)



![Image Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ub9hahxaix4cngtktnw6.jpg)

[Tweet This Blog](https://link.anuvindh.com/twitter/DAY-7-stopinator-2-0.html)  - [Read on GitHub](https://github.com/anuvindhs/100daysofcloud) - [Read On iCTPro.co.nz](https://ictpro.co.nz)

-----


## Stop and Start EC2 instances at predefined times Using Lambda and EventBridge .

Reduce usage of Amazon Elastic Compute Cloud (Amazon EC2) usage by starting and stopping EC2 automatically.

## Step 1 Creating a IAM Poly and execution role for Lambda.

### Create IAM Policy

Goto **IAM** in AWS console and Click **Policies**
and Click **Create Policy**
Click on the **JSON** tab then copy and paste below code 

```JSON
{
  "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 policy as **Stopinator-II** and click **Create**

### Create IAM Role

Go to IAM Console and select **Roles** and click **Create Roles**

|Comments   |  Screenshots |
| ------------ | ------------ |
| Select **AWS Service**  |![Image service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a990q2h6d1ejh5ynv4r4.png) |
|Then Choose **Lambda** and click **next**|![Image lamda2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktd2aljzryytrfinkzgf.png)|
|Search for **AWSLambdaBasicExecutionRole** and select it |![Image policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jef77d7f4vlo2qisebsx.png)|
|Add **Stopinator Policy** also|![Image role2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f57z5a4flo7jd2ves0xr.png)|
|**Name** the role and Click **create role**|![Image namerole](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fasbrwr4vhqybyj95fc7.png)|



### Create an Lambda Function

#### STOP Function
| Comments  | Screenshots  |
| ------------ | ------------ |
| 1. Go to lambda dashboard and click create function| ![Image function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axh1h9u2r8wjowp5kyo7.png)  |
|2. Keep as **Author from scratch** and Name the function|![Image stop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mppv9b12c5ibj3z0wjks.png)|
|3. Select **Runtime**|**Python 3.9**|
|4. **Permissions**, select the created Role|![Image Permissions then click on **create function**](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xubi8pn69kh3xaejv0ge.png)|

Goto **Code** and paste

```python
import boto3
region = 'ap-southeast-2'
instances = ['i-xxxxxxxxxxxxxxxxxx,i-xxxxxxxxxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('stopped your instances: ' + str(instances))
```
**Save** and **Deploy**
Dont forget to add your **instance name** & your **region**

#### START Function

**Repeat** the steps 1 to 4 and add below code to

```python
import boto3
region = 'ap-southeast-2'
instances = ['i-xxxxxxxxxxxxxxxxxx,i-xxxxxxxxxxxxxxxxxx']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))
```

Dont forget to add your **instance name** & your **region**

**Save** and **Deploy**

#### Testing lambda functions
 
Select your function and click test and see the lambda function is working as indented.

## Schedule time to turn ON and OFF EC2 using EventBridge

Goto EventBridge from AWS console and Click **Create rule**

|  Comments | Screenshots  |
| ------------ | ------------ |
| Name the Rule  | ![Image name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4vgvsmj8i6vqy9vmgb7.png)  |
|Define Pattern, Select **Schedule** and enter your **CRON** time. I am keeping 6PM everyday as my stop time .Use this [link](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) to create your cron|![Image cron](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsweku72ivc3vnu2a8v2.png)|
|Select **Target** as your Lambda Function for Stoping|Select **Stopinator-II-Stop**|
|Now click **Create**|![Image Create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lcjcvtxni71jzsd09ziz.png)|
|**Repeat** the steps for |**Strating Instances**|

**Congratulations** you have successfully configured **Stopinator 2.0**



{% user anuvindhs %}