node.js Nodejs - 从另一个 lambda 函数中调用 AWS.Lambda 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35754766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nodejs - Invoke an AWS.Lambda function from within another lambda function
提问by hyprstack
I have the following function which I use to invoke a Lambda function from within my code.
我有以下函数用于从我的代码中调用 Lambda 函数。
However when I try to use it within a Lambda function, I get the following error:
但是,当我尝试在 Lambda 函数中使用它时,出现以下错误:
AWS lambda undefined 0.27s 3 retries] invoke({ FunctionName: 'my-function-name',
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: <Buffer > })
How can I invoke a Lambda function from within a Lambda function?
如何从 Lambda 函数中调用 Lambda 函数?
My function:
我的功能:
'use strict';
var AWS = require("aws-sdk");
var lambda = new AWS.Lambda({
apiVersion: '2015-03-31',
endpoint: 'https://lambda.' + process.env.DYNAMODB_REGION + '.amazonaws.com',
logger: console
});
var lambdaHandler = {};
// @var payload - type:string
// @var functionName - type:string
lambdaHandler.invokeFunction = function (payload, functionName, callback) {
var params = {
FunctionName: functionName, /* required */
InvocationType: "RequestResponse",
LogType: "Tail",
Payload: new Buffer(payload, 'utf8')
};
var lambdaRequestObj = lambda.invoke(params);
lambdaRequestObj.on('success', function(response) {
console.log(response.data);
});
lambdaRequestObj.on('error', function(response) {
console.log(response.error.message);
});
lambdaRequestObj.on('complete', function(response) {
console.log('Complete');
});
lambdaRequestObj.send();
callback();
};
module.exports = lambdaHandler;
回答by nelsonic
Invoking a Lambda Function from within another Lambda function is quite simple using the aws-sdkwhich is available in every Lambda.
使用aws-sdk每个 Lambda 中可用的 ,从另一个 Lambda 函数中调用 Lambda 函数非常简单。
I suggest starting with something simplefirst.
This is the "Hello World" of intra-lambda invocation:
我建议先从简单的事情开始。
这是 lambda 内部调用的“Hello World”:
Lambda_Ainvokes Lambda_Bwith a Payloadcontaining a single parameter name:'Alex'.Lambda_Bresponds with Payload: "Hello Alex".
Lambda_ALambda_B使用Payload包含单个参数的调用name:'Alex'。Lambda_B响应 Payload: "Hello Alex"。


First create Lambda_Bwhich expects a namepropertyon the eventparameter
and responds to request with "Hello "+event.name:
首先创建Lambda_B它期望参数
上的name属性并响应请求:event"Hello "+event.name
Lambda_B
Lambda_B
exports.handler = function(event, context) {
console.log('Lambda B Received event:', JSON.stringify(event, null, 2));
context.succeed('Hello ' + event.name);
};
Ensure that you give Lambda_Band Lambda_Athe same role.
E.g: create a role called lambdaexecutewhich has both AWSLambdaExecuteandAWSLambdaBasicExecutionRole(for some reason both were required):
确保你给予Lambda_B和Lambda_A相同的角色。
例如:创建一个角色lambdaexecute,它同时具有AWSLambdaExecute和AWSLambdaBasicExecutionRole(出于某种原因都需要):


Lambda_A
Lambda_A
var AWS = require('aws-sdk');
AWS.config.region = 'eu-west-1';
var lambda = new AWS.Lambda();
exports.handler = function(event, context) {
var params = {
FunctionName: 'Lambda_B', // the lambda function we are going to invoke
InvocationType: 'RequestResponse',
LogType: 'Tail',
Payload: '{ "name" : "Alex" }'
};
lambda.invoke(params, function(err, data) {
if (err) {
context.fail(err);
} else {
context.succeed('Lambda_B said '+ data.Payload);
}
})
};
Once you have saved both these Lambda functions, Test run Lambda_A:
保存这两个 Lambda 函数后,测试运行Lambda_A:


Once you have the basicintra-lambdda invocation working you can easily extend it to invoke more elaborate Lambda functions.
一旦您拥有基本的内部 lambdda 调用,您就可以轻松扩展它以调用更复杂的 Lambda 函数。
The main thing you have to rememberis to set the appropriate
ARN Rolefor all functions.
您必须记住的主要事情是为所有功能设置适当
ARN Role的。
回答by C.Lee
As of Dec 3, 2016, you can simply use an AWS Step function to put Lambda function Lambda_Bas the sequential step of Lambda_A.
正如2016年12月3日,你可以简单地使用AWS阶跃函数把lambda函数Lambda_B作为的后续步骤,Lambda_A。
With AWS Step Functions, you define your application as a state machine, a series of steps that together capture the behavior of the app. States in the state machine may be tasks, sequential steps, parallel steps, branching paths (choice), and/or timers (wait). Tasks are units of work, and this work may be performed by AWS Lambda functions, Amazon EC2 instances of any type, containers, or on premises servers—anything that can communicate with the Step Functions API may be assigned a task.
使用 AWS Step Functions,您可以将您的应用程序定义为状态机,一系列步骤共同捕获应用程序的行为。状态机中的状态可以是任务、顺序步骤、并行步骤、分支路径(选择)和/或计时器(等待)。任务是工作单元,这项工作可以由 AWS Lambda 函数、任何类型的 Amazon EC2 实例、容器或本地服务器执行——任何可以与 Step Functions API 通信的东西都可以被分配一个任务。
So the following state machine should meet your need.
所以下面的状态机应该可以满足你的需要。
Here is the code corresponding to the state machine.
下面是状态机对应的代码。
{
"Comment": "A simple example of the Amazon States Language using an AWS Lambda Function",
"StartAt": "Lambda_A",
"States": {
"Lambda_A": {
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
"Next": "Lambda_B"
},
"Lambda_B":{
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT_ID:function:FUNCTION_NAME",
"End": true
}
}
}
Moreover, you can add much more sophisticated logics in a state machine, such as parallel steps and catch failures. It even logs the details of every single execution which makes debugging a much better experience, especially for lambda functions.
此外,您可以在状态机中添加更复杂的逻辑,例如并行步骤和捕获失败。它甚至会记录每次执行的详细信息,这使得调试体验更好,尤其是对于 lambda 函数。
回答by Mohammed Asad
Everything mentioned by @nelsonic is correct, except for the roles.
@nelsonic 提到的一切都是正确的,除了角色。
I tried choosing the roles that he mentioned above:
我试着选择他上面提到的角色:
- AWSLambdaExecute
- AWSLambdaBasicExecutionRole
- AWSLambdaExecute
- AWSLambdaBasicExecutionRole
But it did not allow me to invoke my other lambda function, so I changed the role to the below:
但它不允许我调用我的另一个 lambda 函数,所以我将角色更改为以下内容:
- AWSLambdaRole
- AWSLambdaBasicExecutionRole
- AWSLambda角色
- AWSLambdaBasicExecutionRole
The reason behind is AWSLambdaExecuteonly provides Put, Get access to S3 and full access to CloudWatch Logs. but AWSLambdaRoleprovides Default policy for AWS Lambda service role.if you observe its permission policy it will talk about the invokeFunction
背后的原因是AWSLambdaExecute仅提供 Put、Get 访问 S3 和完全访问 CloudWatch Logs。但 AWSLambdaRole为 AWS Lambda 服务角色提供默认策略。如果您遵守其权限政策,它将谈论invokeFunction
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"*"
]
}
]
}
Note: it is OK to proceed without AWSLambdaBasicExecutionRolepolicy as it only enables the logging in the cloud watch nothing much. But AWSLambdaRoleis absolutely necessary.
注意:可以在没有AWSLambdaBasicExecutionRole策略的情况下继续进行,因为它只启用了云中的日志记录。但是AWSLambdaRole是绝对必要的。

