AWS Lambda - Invoke a method of another lambda function

南楼画角 提交于 2021-02-08 06:24:14

问题


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


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/59072269/aws-lambda-invoke-a-method-of-another-lambda-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!