Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and stop EC2 instance using Lambda

I am trying to start and stop an EC2 windows instance using lambda, i am using Node.js 8.10 to write the start and stop script.When i am testing the script the script is executed successfully but the EC2 instance is not effected.I am giving the instance details and script below

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

exports.handler = async (event) => {

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));
};

The script executed successfully

enter image description here

Below is the instance details enter image description here

This is stop script but this is not able to stop the instance , please help me i am new to aws . Thanks in advance

like image 606
Mandrek Avatar asked May 11 '26 02:05

Mandrek


1 Answers

When using Lambda, your handler function receives three parameters: event, context and callback. You make use of callback when using synchronous functions. When using async you should return a promise.

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

exports.handler = async (event, context, callback) => {

const ec2 = new AWS.EC2({ region: event.instanceRegion });
 return ec2.stopInstances({ InstanceIds: [event.instanceId] }).promise()
    .then(() => `Successfully stopped ${event.instanceId}`)
    .catch(err => console.log(err));
};

In fact, when you use async keyword you are actually returning a promise, but by returning nothing, you are resolving it with null as response, so your code will just terminate and your stopInstances will not finish their work.

like image 104
guijob Avatar answered May 12 '26 16:05

guijob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!