DEV Community

Cover image for Stop and Start EC2 instances at predefined times Using Lambda and EventBridge - STOPINATOR 2.0
Anuvindh for AWS Community Builders

Posted on • Updated on

Stop and Start EC2 instances at predefined times Using Lambda and EventBridge - STOPINATOR 2.0

DAY 7 - Stop and Start EC2 instances at predefined times Using Lambda and EventBridge - STOPINATOR 2.0

☁️100 days of Cloud- Day Seven
Follow Me on Twitter

Image Cover

Tweet This Blog - Read on GitHub - Read On 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

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

Enter fullscreen mode Exit fullscreen mode

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
Then Choose Lambda and click next Image lamda2
Search for AWSLambdaBasicExecutionRole and select it Image policy
Add Stopinator Policy also Image role2
Name the role and Click create role Image namerole

Create an Lambda Function

STOP Function

Comments Screenshots
1. Go to lambda dashboard and click create function Image function
2. Keep as Author from scratch and Name the function Image stop
3. Select Runtime Python 3.9
4. Permissions, select the created Role Image Permissions then click on **create function**

Goto Code and paste

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))
Enter fullscreen mode Exit fullscreen mode

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

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))
Enter fullscreen mode Exit fullscreen mode

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
Define Pattern, Select Schedule and enter your CRON time. I am keeping 6PM everyday as my stop time .Use this link to create your cron Image cron
Select Target as your Lambda Function for Stoping Select Stopinator-II-Stop
Now click Create Image Create
Repeat the steps for Strating Instances

Congratulations you have successfully configured Stopinator 2.0

Top comments (2)

Collapse
 
megaproaktiv profile image
Gernot Glawe

Nice post!
If you want to do this at scale, there is an AWS solution premade: aws.amazon.com/de/solutions/implem...

Collapse
 
anuvindhs profile image
Anuvindh

Thanks Gernot