[英]Call a nested function in AWS lambda
I have a AWS Lambda function that checks if a site is online我有一个 AWS Lambda function 检查网站是否在线
var http = require('https');
var url = 'https://www.google.com';
exports.handler = function(event, context) {
http.get(url, function(res) {
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
}
I would like to reboot an EC2 instance if the website is offline.如果网站离线,我想重新启动 EC2 实例。 This is the Lambda function to reboot EC2:
这是 Lambda function 重新启动 EC2:
var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var ec2 = new AWS.EC2({region: 'us-east-1'});
ec2.rebootInstances({InstanceIds : ['i-xxxxxxxxxxxxxxx'] },function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
context.done(err,data);
});
};
Both functions work.这两个功能都有效。 Now I am trying to call the ec2 reboot function when the https request fails.
现在,当 https 请求失败时,我尝试调用 ec2 reboot function。
I have an extremely limited experience with node.js and aws so I tried many different ways but no result.我对 node.js 和 aws 的经验非常有限,所以我尝试了许多不同的方法,但没有结果。
Can someone point me in the right direction?有人可以指出我正确的方向吗?
you can invoke a lambda using the invoke function.您可以使用调用 function 调用 lambda。
function checkWebsite(url, callback) {
https
.get(url, function(res) {
console.log(url, res.statusCode);
return callback(res.statusCode === 200);
})
.on("error", function(e) {
return callback(false);
});
}
var http = require('https');
exports.handler = function(event, context, callback) {
var url = 'https://www.google.com';
checkWebsite(url, (check) => {
if (!check) {
const lambda = new AWS.Lambda();
const params = {
FunctionName: "my-function",
Payload: '{"instanceId":"instance-1233x5"}'
};
lambda.invoke(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
// handle error/ success
// if you return the error, the lambda will be retried, hence returning a successful response
callback(null, 'successfully rebooted the instance')
});
} else {
callback(null, 'successfully completed')
}
})
}
Reference: Nodejs function to check if a website working参考: Nodejs function 检查网站是否工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.