Reputation: 2219
I try to invoke a “child” lambda from a “parent” lambda
The example of code is very simple as below (I am using Serverless framework).
child_lambda
const mainHandler = async (event, context) => {
console.log('event: ', JSON.stringify(event));
return context.functionName;
};
export const handler = mainHandler;
parent_lambda
import AWS from 'aws-sdk';
const lambda = new AWS.Lambda();
const invokeLambda = async () => {
let sampleData = { number1: 1, number2: 2 };
let params = {
FunctionName: 'child_lambda',
Payload: JSON.stringify(sampleData),
Qualifier: '1'
};
try {
await lambda.invoke(params).promise();
return true;
} catch (e) {
console.log('invokeLambda :: Error: ' + e);
}
};
const mainHandler = async (event, context) => {
console.log('event: ', JSON.stringify(event));
await invokeLambda();
return context.functionName;
};
export const handler = mainHandler;
serverless.yml
parent_lambda:
handler: handlers/lambda/parent_lambda.handler
name: dev_parent_lambda
iamRoleStatements:
- Effect: "Allow"
Action:
- lambda: InvokeFunction
- lambda: InvokeAsync
Resource: "*"
events:
- http:
path: test/invokeLambda
method: GET
child_lambda:
handler: handlers/lambda/child_lambda.handler
name: dev_child_lambda
I run the parent from Postman and the result is
ResourceNotFoundException: Function not found: arn:aws:lambda:xxxx:xxxxx:function:dev_child_lambda
I tried to trigger the child_lambda from an S3 event, it worked fine, but never work with invoke
as AWS SDK.
Any suggestion is appreciated
Upvotes: 2
Views: 12683
Reputation: 9625
Lambda Asynchronous invocation
Amazon Simple Storage Service (Amazon S3) invoke functions asynchronously to process events. When you invoke a function asynchronously, you don't wait for a response from the function code. You hand off the event to Lambda and Lambda handles the rest.
In that case, I would simply chain the lambdas using AWS lambda destinations. Supported destinations:
Amazon SQS – sqs:SendMessage
Amazon SNS – sns:Publish
Lambda – lambda:InvokeFunction
EventBridge – events:PutEvents
Configuring destinations for asynchronous invocation
Introducing AWS Lambda Destinations
Upvotes: 0
Reputation: 10333
From the comments, code given in the question is perfect except the Qualifier parameter
Qualifier is used to
Specify a version or alias to invoke a published version of the function.
In this case, lambda is not versioned. Hence we just need to remove qualifier .
const invokeLambda = async () => {
let sampleData = { number1: 1, number 2: 2 };
let params = {
FunctionName: 'child_lambda',
Payload: JSON.stringify(sampleData)
};
try {
await lambda.invoke(params).promise();
return true;
} catch (e) {
console.log('invokeLambda :: Error: ' + e);
}
};
Upvotes: 2