AWS Lambda to invoke other lambda function asynchronously in same region using Java

Swapnil Watkar
4 min readJun 29, 2022

--

In this article we will see how we can call another lambda function in same region using InvokeRequest.

To explain this we will create one Lambda function to write hello world, and will call this function from another lambda function. We need two dependencies aws-lambda-java-core,aws-java-sdk-lambda in order to do
this task. InvokeRequest is present in aws-java-sdk-lambda which helps to invoke another lambda by passing function name.

We will write a handler code in java for this.

Our code will have below steps:
1. The AWS Region in which the function is to be invoked.
2. Instantiate AWSLambdaClientBuilder to build the Lambda client.
3. Build the client, which will ultimately invoke the function.
4. Create an InvokeRequest with required parameters.
5. Invoke the function and get response.

Steps to done.

1. Create IAM role for Lambda.
2. Create a lambda function which we want to invoke.
3. Create a lambda function using InvokeRequest.
4. Handle Response.

Create IAM role for Lambda:

Go to AWS Console, type IAM and click the IAM service.
This will open the IAM service page.
Click the Roles from the left menu to display the Roles under Access management.
Click the Create role button on right.

Follow the steps to create role :

1.Select AWS service as a trusted entity.
2.Select Lambda in the list of services and click on the Next.
3.Add permissions (AWSLambdaBasicExecutionRole).
4.Add inline policy as shown below. (Click Create inline policy)

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": "arn:aws:lambda:*:*:*"
}
]
}

5.done.

Create a lambda function which we want to invoke:

1. Type lambda in the console to list the lambda service and select it.
2. Click the Create function to generate new lambda function.
3. In Basic information give the function Name,Runtime (Java 8).
4. Default Advanced settings.
5. Click Create function.

Create a jar file containing the handler class with the code to display Hello world. Upload this jar in the code section of Lambda function.

import com.amazonaws.services.lambda.runtime.Context;

public class LamdaExample
{
String text="Invoking the Lambda";

public Boolean handler(Context context){
context.getLogger().log("Function name: "+ context.getFunctionName()+"\n" );
context.getLogger().log( "Invoke message: "+text+"\n" );
return true;
}
}

Create a lambda function using InvokeRequest:

1. Type lambda in the console to list the lambda service and select it.
2. Click the Create function to generate new lambda function.
3. In Basic information give the function Name,Runtime (Java 8),Existing execution role (previously created).
4. Default Advanced settings.
5. Click Create function.

Next we need to create a jar and upload in our lambda function.

Steps to create a jar:

Create maven project using quick start in any IDE (Eclipse,IntelliJ).
Provide dependencies for aws-lambda-java-core and aws-java-sdk-lambda in POM.xml.

Write a code below in the handler class.
Replace your credentials below.

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.lambda.AWSLambdaClient;
import com.amazonaws.services.lambda.model.InvokeRequest;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.nio.ByteBuffer;


public class LambdaToLambda implements RequestHandler {
private static final AmazonS3 s3client=AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("<youraccesskey>", "<yoursecretkey>"))))
.withRegion("us-east-1").build();
String functionName = "<your function ARN>";
String inputJSON = "{\"Name\":\"Swapnil\",\"lastName\": \"Watkar\"}";
@Override
public String handleRequest(Object input, Context context) {

AWSLambdaClient lambdaClient = new AWSLambdaClient();
try {
InvokeRequest invokeRequest = new InvokeRequest();
invokeRequest.setFunctionName(functionName);
invokeRequest.setPayload(inputJSON);
ByteBuffer payload = lambdaClient.invoke(invokeRequest).getPayload();
context.getLogger().log(payload.toString());

} catch (Exception e) {
context.getLogger().log(" --Exception-- "+e.getMessage());
}
return "Invoking other lambda MyLambdaFunction ";
}
}

Build the project and Generate the jar.

mvn clean package

Upload jar to our Lambda function

Open the lambda function and go to the code section click on Upload from button. Select the jar created for lambda. upload it.

Edit runtime settings in code section
edit the handler name <package><classname>::handleRequest

Save changes.

Test the scenario:

To test our code go to our Lambda function which has InvokeRequest , then go to Test section.

we will do a default setting as below, click Test button. Check Result (below screen shot show invoking lambda function executed successfully)

However actual result will be seen in the Cloudwatch logs for the Lambda(which we want to invoke)

Thank you!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Swapnil Watkar
Swapnil Watkar

Written by Swapnil Watkar

Hi ! I am a Software Consultant , experienced in Mobile and Web applications Also AWS Certified Solutions Architect — Associate

No responses yet

Write a response