为什么我的代码可以在标准Node.js文件中运行,但不能在AWS Lambda函数中运行? [英] Why can my code run in a standard Node.js file, but not in a AWS Lambda Function?

查看:78
本文介绍了为什么我的代码可以在标准Node.js文件中运行,但不能在AWS Lambda函数中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是创建一个lambda函数,该函数在ec2实例上调用两个命令.当我无法在lambda函数中运行此代码时,我从exports.handler()方法中删除了该代码,并在同一ec2实例中的独立node.js文件中运行了该代码,我得以使代码正常工作.我运行的命令是"node app.js".

What I'm trying to do is create a lambda function where the function calls two commands on an ec2 instance. When I had trouble running this code in a lambda function, I removed the code from the exports.handler() method and ran the code in a standalone node.js file in the same ec2 instance and I was able to get the code to work. The command I ran was 'node app.js'.

exports.handler = async (event) => {

  const AWS = require('aws-sdk')
  AWS.config.update({region:'us-east-1'});

  var ssm = new AWS.SSM();

  var params = {
  DocumentName: 'AWS-RunShellScript', /* required */
  InstanceIds: ['i-xxxxxxxxxxxxxxxx'],
  Parameters: {
    'commands': [
      'mkdir /home/ec2-user/testDirectory',
      'php /home/ec2-user/helloWorld.php'
      /* more items */
    ],
    /* '<ParameterName>': ... */
  }
};
ssm.sendCommand(params, function(err, data) {
  if (err) {
    console.log("ERROR!");
    console.log(err, err.stack); // an error occurred
  }
  else {
  console.log("SUCCESS!");
  console.log(data);
  }            // successful response
});


  const response = {
    statusCode: 200,
    ssm: ssm
  };

  return response;
}; 

我认为这可能是与权限相关的问题,但是lambda与ec2实例所在的同一vpc不同.

I figured that it could have been a permissions related issue, but the lambda is apart of the same vpc that the ec2 instance is in.

推荐答案

您正在尝试将async/await与回调结合在一起.这在lambda AWS Lambda Function Handler在Node中不起作用. js .它在本地或节点服务器中工作的原因是,当函数退出时,服务器仍在运行,因此回调仍然发生.在Lambda中,如果您使用的是async(或Promises),则Lambda退出后,节点进程将消失,因此无法触发回调.

You're trying to combine async/await with callbacks. That won't work in a lambda AWS Lambda Function Handler in Node.js. The reason it's working locally, or in a node server, is because the server is still running when the function exits, so the callback still happens. In a Lambda the node process is gone as soon as the lambda exits if you are using async (or Promises), so the callback is not able to be fired.

这篇关于为什么我的代码可以在标准Node.js文件中运行,但不能在AWS Lambda函数中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆