Nodejs – Invoke an AWS.Lambda function from within another lambda function

Invoking a Lambda Function from within another Lambda function is quite simple using the aws-sdk which is available in every Lambda.

I suggest starting with something simple first.
This is the “Hello World” of intra-lambda invocation:

Lambda_A invokes Lambda_B
with a Payload containing a single parameter name:'Alex'.
Lambda_B responds with Payload: "Hello Alex".

lambda invoke

First create Lambda_B which expects a name property
on the event parameter
and responds to request with "Hello "+event.name:

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_B and Lambda_A the same role.
E.g: create a role called lambdaexecute which has AWSLambdaRole, AWSLambdaExecute and
AWSLambdaBasicExecutionRole (All are required):

lambda-role-for-intra-lambda-execution

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 invoke-lambda_a-execution-result

Once you have the basic intra-lambdda invocation working you can easily extend it to invoke more elaborate Lambda functions.

The main thing you have to remember is to set the appropriate ARN Role for all functions.

Leave a Comment