Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (5.6k points)

I need to start and stop EC2 instances using lambda, & for this, I'm using Node.js to write the script. But when executing the script it is not affected. I'm providing the 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));

};

Please help me to resolve this issue.

1 Answer

0 votes
by (12.4k points)
edited by

You can make use of 'callback' when using the synchronous functions, when using async you should return a promise, like:

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

};

Actually here when you use 'async' you are returning nothing but "null" as a response so it will just terminate and the 'stop instance' will not finish its work.

Do Check out the AWS Certification Course offered by Intellipaat. 

For learning more about AWS Lambda, do watch the video tutorial below:

Related questions

0 votes
1 answer
Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...