Lambda_Start_Stop_EC2_With_CloudWatch

Lambda_Start_Stop_EC2_With_CloudWatch

Lambda Function for Start_Stop_EC2 instance and attached to CloudWatch and scheduled to start Stop automatic on define time.

In side IAM role create Policies

Service:- EC2
Actions
Write
StartInstances
StopInstances
Resources :- All resources

 

Next, In roles “create role” and then select “Lambda” then “Permission” then select a policy from the list.

Give role name and click create

Give a name to the role.

 

Next in Lambda “Create a function”

In index.js put below code.

const AWS = require('aws-sdk');

exports.handler = (event, context, callback) => {
    const ec2 = new AWS.EC2({ region: event.instanceRegion });
    ec2.stopInstances({ InstanceIds: [event.instanceId] }).promise()
        .then(() => callback(null, `Successfully stopped ${event.instanceId}`))
        .catch(err => callback(err));

};

Create a testing case.

Test case looks like.

{
  "instanceRegion": "us-east-2",
  "instanceId": "i-004f28d6362128cc8"
}

Check test result.

Response:
"Successfully stopped i-004f28d6362128cc8"
Request ID:
"02f1a0e4-d27d-409c-ab6c-dab867ba2810"
Function Logs:
START RequestId: 02f1a0e4-d27d-409c-ab6c-dab867ba2810 Version: $LATEST
END RequestId: 02f1a0e4-d27d-409c-ab6c-dab867ba2810
REPORT RequestId: 02f1a0e4-d27d-409c-ab6c-dab867ba2810      Duration: 2248.11 ms     Billed Duration: 2300 ms          Memory Size: 128 MB    Max Memory Used: 75 MB          

On AWS console we can see instance going to stopping.

Create the same for start instance.

For start past below code

const AWS = require('aws-sdk');

exports.handler = (event, context, callback) => {
    const ec2 = new AWS.EC2({ region: event.instanceRegion });
    ec2.startInstances({ InstanceIds: [event.instanceId] }).promise()
        .then(() => callback(null, `Successfully started ${event.instanceId}`))
        .catch(err => callback(err));
};

Create the same test instance. Now you can see EC2 instance started.

For scheduling these process we under “Cloud Watch”  rules. Create a rule.

Provide a name.

Create same for the stop.

 

Leave a Reply

Your email address will not be published. Required fields are marked *