Skip to content

Instantly share code, notes, and snippets.

@juno
Last active April 17, 2024 12:23
Show Gist options
  • Save juno/b5fc38b53e8833c18b43 to your computer and use it in GitHub Desktop.
Save juno/b5fc38b53e8833c18b43 to your computer and use it in GitHub Desktop.
AWS Lambda Function to call EC2 StartInstances/StopInstances API
/* Event Parameters
{
"accessKeyId": "...",
"secretAccessKey": "...",
"region": "ap-northeast-1",
"instanceId": "i-XXXXXXXX"
}
*/
exports.handler = function(event, context) {
console.log('instanceId =', event.instanceId);
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: event.accessKeyId, secretAccessKey: event.secretAccessKey, region: event.region});
var ec2 = new AWS.EC2();
var params = {
InstanceIds: [event.instanceId],
DryRun: false
};
ec2.startInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack);
context.fail(err);
} else {
console.log(data);
context.succeed(data);
}
});
};
/* Event Parameters
{
"accessKeyId": "...",
"secretAccessKey": "...",
"region": "ap-northeast-1",
"instanceId": "i-XXXXXXXX"
}
*/
exports.handler = function(event, context) {
console.log('instanceId =', event.instanceId);
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: event.accessKeyId, secretAccessKey: event.secretAccessKey, region: event.region});
var ec2 = new AWS.EC2();
var params = {
InstanceIds: [event.instanceId],
DryRun: false,
Force: true
};
ec2.stopInstances(params, function(err, data) {
if (err) {
console.log(err, err.stack);
context.fail(err);
} else {
console.log(data);
context.succeed(data);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment