首页 > 解决方案 > 在 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 reboot 函数。

我对 node.js 和 aws 的经验非常有限,所以我尝试了很多不同的方法,但没有结果。

有人可以指出我正确的方向吗?

标签: node.jsamazon-web-servicesaws-lambdahttprequest

解决方案


您可以使用调用函数调用 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 函数检查网站是否正常工作


推荐阅读