Shashikant Kulkarni
Shashikant Kulkarni

Reputation: 177

AWS Lambda - Invoke a method of another lambda function

I am trying to invoke a method, different than the default handler method, of one lambda from another lambda. But not getting how to do it. It is not clear from the documentation. Here is my code

Lambda function 1: my_function1

import json
import boto3

def lambda_handler(event, context):
    lambda_inv = boto3.client("lambda", region_name="us-east-1")
    payload = {"message":"Hi From my_function1"}
    lambda_inv.invoke(FunctionName='arn:aws:lambda:us-east-1:1236547899871:function:my_function2', 
                        InvocationType='Event', Payload=json.dumps(payload))


Lambda function 2: my_function2

import json

def lambda_handler(event, context):
    # TODO implement
    print("lambda_handler")

def say_hello(event, context):
    print("From say_hello function")
    print(str(event))
    print("say_hello end")

I want to invoke say_hello method of lambda my_function2 from lambda my_function1. How do I do that? By default it tries to invoke the default lambda_handler method

Upvotes: 2

Views: 2077

Answers (2)

Branson Smith
Branson Smith

Reputation: 482

Lambda Functions are always entered through the handler function. It is like the 'main method'. Each Lambda Function is its own application, with its own resources, so when you coordinate between them, you will always enter the function through main (the handler), where you can then go anywhere else.

Remember each Lambda loses all of its resources (Memory and CPU) in-between getting called, so it will always reboot from the handler on each call.

To get to your say_hello function, you'll need to use some if statements in the handler like @jimmone described. Something like this:

def lambda_handler(event, context):
    lambda_inv = boto3.client("lambda", region_name="us-east-1")
    payload = {
        "message":"Hi From my_function1", 
        "request": "say_hello"
    }
    lambda_inv.invoke(FunctionName='arn:aws:lambda:us-east- 1:1236547899871:function:my_function2', 
                        InvocationType='Event', Payload=json.dumps(payload))


def lambda_handler(event, context):
    # TODO implement
    print("lambda_handler")
    if event['request'] == 'say_hello':
        return say_hello(event, context)

def say_hello(event, context):
    print("From say_hello function")
    print(str(event))
    print("say_hello end")

If you are just wanting to change the name of the handler, that can be done by editing the Handler option in AWS Lambda. In this case my_function2.say_hello enter image description here

Upvotes: 1

jimmone
jimmone

Reputation: 466

You can have only 1 handler per lambda function. What you can do is having some if-logic in your handler to call different functions within the same lambda based on the event.

Upvotes: 3

Related Questions