提问者:小点点

调用AWS lambda中的嵌套函数


我有一个AWS Lambda函数来检查站点是否在线

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

我想重新启动一个EC2实例,如果网站是脱机的。这是重启EC2的Lambda函数:

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

这两个功能都起作用。现在我尝试在https请求失败时调用ec2重启函数。

我使用Node.js和aws的经验非常有限,所以我尝试了许多不同的方法,但都没有结果。

有人能给我指个正确的方向吗?


共1个答案

匿名用户

您可以使用invoke函数调用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')
    }
  })
}

参考:Nodejs检查网站是否正常工作的功能