sid8491
sid8491

Reputation: 6800

call method of lambda function from another lambda function - Python

I am able to call lambda function from another lambda function but by default it goes to handler method. How do I invoke some other method defined in it?

Suppose there is lambda function master.py, which will have common methods which can be used by other lambda functions so that I don't have to write them again and again in every function. Now I want to call methods of master.py (lets say getTime(), authenticateUser() etc) from other lambda functions.

Basically I want to keep a lambda function which will have common methods which can be used by other lambda functions.
Any help is appreciated.

Below is the code I have tried to call one lambda function from another (i have taken code from this question) but it goes to handler() method:

lambda function A

def handler(event,context):
    params = event['list']
    return {"params" : params + ["abc"]}

lambda function B invoking A

import boto3
import json

lambda_client = boto3.client('lambda')
a=[1,2,3]
x = {"list" : a}
invoke_response = lambda_client.invoke(FunctionName="functionA",
                                       InvocationType='RequestResponse',
                                       Payload=json.dumps(x))
print (invoke_response['Payload'].read())

Output

{
  "params": [1, 2, 3, "abc"]
}

Upvotes: 1

Views: 8382

Answers (1)

Fowler
Fowler

Reputation: 524

You can pass the data needed to run your desired lambda function method within the event parameter upon calling invoke. If you include the following code in the top of your lambda_handler from the lambda function with the method you would like to invoke.

def lambda_handler(event, context):
    """
    Intermediary method that is invoked by other lambda functions to run methods within this lambda
    function and return the results.

    Parameters
    ----------
    event : dict
            Dictionary specifying which method to run and the arguments to pass to it
            {function: "nameOfTheMethodToExecute", arguments: {arg1: val1, ..., argn: valn}}
    context : dict
            Not used

    Returns
    -------
    object : object
            The return values from the executed function. If more than one object is returned then they
            are contained within an array.
    """
    if "function" in event:
         return globals()[event["function"]](**event["arguments"])
    else:
        # your existing lambda_handler code...

Then, to call the method and get the return values from your other lambda function using the following method invoke.

import json

# returns the full name for a lambda function from AWS based on a given unique part
getFullName = lambda lambdaMethodName: [method["FunctionName"] for method in lambda_client.list_functions()["Functions"] if lambdaMethodName in method["FunctionName"]][0]

# execute a method in a different lambda function and return the results
def invoke(lambda_function, method_name, params):
    # wrap up the method name to run and its parameters
    payload = json.dumps({"function": method_name, "arguments": params})
    # invoke the function and record the response
    response = lambda_client.invoke(FunctionName=getFullName(lambda_function), InvocationType='RequestResponse', Payload=payload)
    # parse the return values from the response
    return json.loads(response["Payload"].read())


[rtn_val_1, rtn_val_2] = invoke("fromLambdaA", "desiredFunction", {arg1: val1, arg2: val2})

Note your lambda policy attached to the function that is invoking the other lambda function will need two polices: "lambda:ListFunctions" and "lambda:InvokeFunction"

Upvotes: 2

Related Questions