欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

程序员文章站 2024-01-22 23:26:46
...

lambda调用函数

In this article, I am going to explain how to create an AWS Lambda function and then call this function from another Lambda function within the same region. This is a useful scenario in which we may need to execute a second lambda function based on the outcome of some previous logic. Another scenario may be to execute a second lambda function several times by using different parameters.

在本文中,我将解释如何创建一个AWS Lambda函数,然后从同一区域内的另一个Lambda函数调用此函数。 这是一个有用的场景,其中我们可能需要根据某些先前逻辑的结果执​​行第二个lambda函数。 另一种情况可能是使用不同的参数多次执行第二个lambda函数。

For the sake of this article, we will consider a typical retailer application, in which we can purchase different products from a retailer site using a lambda function.

为了本文的目的,我们将考虑一个典型的零售商应用程序,在该应用程序中,我们可以使用lambda函数从零售商站点购买不同的产品。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

If you consider the above architecture diagram, you can see that we have an AWS lambda function – the ParentFunction, which assumes a specific role from the IAM (Invoke Other Lambda Function) and then calls another lambda function – the ChildFunction with a payload. Once the execution of the ChildFunction is completed, it returns a response, which is then passed on to the ParentFunction. The ParentFunction receives the response and handles the job accordingly.

如果考虑以上架构图,您会看到我们有一个AWS lambda函数– ParentFunction ,它从IAM( 调用其他Lambda函数 )承担特定角色,然后调用另一个lambda函数–带有有效负载的ChildFunction 。 一旦ChildFunction的执行完成,它将返回一个响应,然后将其传递给ParentFunctionParentFunction接收响应并相应地处理作业。

As in this example, let us assume that the ParentFunction is going to call the ChildFunction with a payload of ProductName, Quantity, and the UnitPrice of that product. The ChildFunction, in turn, will process this payload, calculate the total sales amount, generate a transaction reference ID, and return this information to the ParentFunction.

在此示例中,让我们假设ParentFunction将使用该产品的ProductName,Quantity和UnitPrice的有效负载来调用ChildFunction 。 反过来, ChildFunction将处理此有效负载,计算总销售额,生成交易参考ID,并将此信息返回给ParentFunction

创建第一个AWS Lambda函数– ChildFunction (Creating the first AWS Lambda Function – ChildFunction)

Let us first go ahead and create the ChildFunction, which will process the input payload and return the results to the ParentFunction.

让我们首先继续创建ChildFunction,该函数将处理输入的有效负载并将结果返回给ParentFunction。

Head over to https://console.aws.amazon.com/ and login with your credentials. Once you are inside the console, start searching for “Lambda” and click on the first result that appears from the drop-down.

转到https://console.aws.amazon.com/并使用您的凭据登录。 进入控制台后,开始搜索“ Lambda ”,然后单击下拉菜单中显示的第一个结果。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

This will take you to the Lambda Function homepage, where you can create a new lambda function by hitting the “Create Function” button.

这将带您到Lambda函数主页,您可以在其中单击“ 创建函数 ”按钮来创建新的lambda函数。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Let the name of this function be – “ChildFunction” and select Python 3.8 as the runtime.

将该函数的名称设为–“ ChildFunction”,然后选择Python 3.8作为运行时。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Select the option to Create a new role with basic lambda permissions and click on Create Function.

选择选项以创建具有基本lambda权限的新角色,然后单击创建功能

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

A new lambda function will be created where you can write your code and test it.

将创建一个新的lambda函数,您可以在其中编写代码并对其进行测试。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Let us now head over to Visual Studio Code and start writing our code for the ChildFunction as follows. This is a very simple application that is going to perform the following steps:

现在让我们转到Visual Studio Code,并开始为ChildFunction编写我们的代码,如下所示。 这是一个非常简单的应用程序,它将执行以下步骤:

  1. Read data from the ParentFunction

    从ParentFunction读取数据
  2. Generate the Transaction Reference ID

    产生交易参考编号
  3. Calculate the business information

    计算业务信息
  4. Return the result to the Parent Function

    将结果返回给父函数

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数
import json
import uuid
 
def lambda_handler(event, context):
    #1 Read the input parameters
    productName = event['ProductName']
    quantity    = event['Quantity']
    unitPrice   = event['UnitPrice']
 
    #2 Generate the Order Transaction ID
    transactionId   = str(uuid.uuid1())
 
    #3 Implement Business Logic
    amount      = quantity * unitPrice
 
    #4 Format and return the result
    return {
        'TransactionID' :   transactionId,
        'ProductName'   :   productName,
        'Amount'        :   amount
    }
 
#########################################################################
# No need to include the following snippet into the lambda function
# Only used to test the function locally
event = {
    "ProductName"   : "iPhone SE",
    "Quantity"      : 2,
    "UnitPrice"     : 499
}
response = lambda_handler(event,'')
print(response)
#########################################################################

Once the code is written and tested in the local machine, you can copy and paste the script to the lambda function to test it in AWS.

在本地计算机中编写和测试代码后,您可以将脚本复制并粘贴到lambda函数以在AWS中对其进行测试。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

In order to test the ChildFunction, you need to create the Test Event, in which you can pass the payload information that we will be using to call from the ParentFunction. In order to configure test events, click on Test Event, and select Configure.

为了测试ChildFunction,您需要创建Test Event,在其中您可以传递我们将用于从ParentFunction调用的有效负载信息。 为了配置测试事件,请单击测试事件,然后选择配置

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Give the test event a name and specify the payload information here to test it.

为测试事件命名,并在此处指定有效负载信息以对其进行测试。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Hit on Test to execute the ChildFunction with the payload information.

点击测试以使用有效负载信息执行ChildFunction

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

If the execution is successful, you will get a successful return with the calculations completed as follows. As you can see in the figure below, the function returns the following items.

如果执行成功,您将获得成功的回报,并完成以下计算。 如下图所示,该函数返回以下项目。

  1. Transaction ID

    交易编号
  2. Product Name

    产品名称
  3. Amount

This information will also be visible to the ParentFunction when it calls the ChildFunction.

当父函数调用子函数时,此信息也将对父函数可见。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Also, copy the ARN of the Child Function, which can be used later to apply for policies and roles upon.

同样,复制子功能的ARN,以后可用于在其上申请策略和角色。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

设置ParentFunction的策略 (Setting up the Policy for ParentFunction)

In order to allow the ParentFunction to call the ChildFunction, we need to provide the ParentFunction with specific rights to call another lambda function. This can be done by adding specific policies to a role and then assign that role to the lambda function.

为了允许ParentFunction调用ChildFunction,我们需要为ParentFunction提供特定的权限来调用另一个lambda函数。 这可以通过向角色添加特定策略,然后将该角色分配给lambda函数来完成。

Head over to the IAM module inside the AWS portal and select Policies. Click on Create Policy to create a new one.

转到AWS门户内的IAM模块,然后选择策略 。 单击创建策略以创建一个新策略

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

In the Create Policy page, select the JSON tab and add the following policy summary to it as follows. Remember to update the URL for the Resource which you have copied in the previous step. Give the policy a suitable name and create it. I am going to name this policy as – “InvokeOtherLambdaPolicy”.

在“创建策略”页面中,选择“ JSON”选项卡,并向其添加以下策略摘要,如下所示。 记住要更新在上一步中复制的资源的URL。 为策略指定一个合适的名称并创建它。 我将这个策略命名为–“ InvokeOtherLambdaPolicy ”。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Navigate to the Roles and click on Create role.

导航到“ 角色” ,然后单击“ 创建角色”

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Select Lambda as the use case and click on Next to add the required permissions.

选择Lambda作为用例,然后单击“下一步”添加所需的权限。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Add the following two policies to this role and create the role.

将以下两个策略添加到该角色并创建该角色。

  1. AWSLambdaBasicExecutionRole

    AWSLambdaBasicExecutionRole
  2. InvokeOtherLambdaPolicy

    调用其他Lambda政策

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Click on Next and proceed forward and create the role. Give this role a suitable name, for example, “InvokeOtherLambdaRole”.

单击下一步,然后继续并创建角色。 给该角色指定一个合适的名称,例如“ InvokeOtherLambdaRole ”。

创建AWS Lambda函数– ParentFunction (Creating the AWS Lambda Function – ParentFunction)

Head over to the Lambda Function page and click on Create New Lambda function. I am calling this lambda function – “ParentFunction”. Choose the run time as Python 3.8 and assign the InvokeOtherLambdaRole role that we just created in the previous step.

转到Lambda函数页面,然后单击创建新 Lambda函数。 我称这个lambda函数为“ ParentFunction ”。 选择运行时作为Python 3.8,并分配我们在上一步中刚刚创建InvokeOtherLambdaRole角色。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Let us now again head over to Visual Studio Code to write the code and then copy-paste it back to the lambda editor. Since we are going to use an AWS resource in this function, we need to use the Boto3 python library to use the AWS resources. This library can be used to interact with other AWS resources as and when required.

现在让我们再次转到Visual Studio Code来编写代码,然后将其复制粘贴回lambda编辑器。 由于我们将在此函数中使用AWS资源,因此我们需要使用Boto3 python库来使用AWS资源。 必要时,该库可用于与其他AWS资源进行交互。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数
import json
import boto3
 
# Define the client to interact with AWS Lambda
client = boto3.client('lambda')
 
def lambda_handler(event,context):
 
    # Define the input parameters that will be passed
    # on to the child function
    inputParams = {
        "ProductName"   : "iPhone SE",
        "Quantity"      : 2,
        "UnitPrice"     : 499
    }
 
    response = client.invoke(
        FunctionName = 'arn:aws:lambda:eu-west-1:890277245818:function:ChildFunction',
        InvocationType = 'RequestResponse',
        Payload = json.dumps(inputParams)
    )
 
    responseFromChild = json.load(response['Payload'])
 
    print('\n')
    print(responseFromChild)

As you can see in the above code, we have created a boto client to interact with the lambda function. Also, we have created a payload that can be passed on to the ChildFunction when calling it. And once the ChildFunction is executed, it will return the response, which will be stored in the “response” variable.

如您在上面的代码中看到的,我们创建了一个boto客户端来与lambda函数进行交互。 同样,我们创建了一个有效载荷,可以在调用它时将其传递给ChildFunction。 并且一旦执行ChildFunction,它将返回响应,该响应将存储在“ response”变量中。

Finally, we can parse the payload information from the response and use it according to our needs. In this case, we are just going to print it on the screen. Copy the code from VS Code to the lambda editor.

最后,我们可以从响应中解析有效负载信息,并根据需要使用它。 在这种情况下,我们只是将其打印在屏幕上。 将代码从VS Code复制到lambda编辑器。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Create a sample test event for this function since we are not going to pass any payload for this Parent Function here. Save the event and click on the Test.

为此函数创建一个示例测试事件,因为在这里我们不会传递此父函数的任何有效负载。 保存事件,然后单击“ 测试”

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

Once you execute the ParentFunction, it will pass the payload information to the ChildFunction, where the result will be calculated, and then the final response will be sent back from the ChildFunction to the ParentFunction. You can see the execution logs and confirm this as follows.

一旦执行ParentFunction,它将把有效负载信息传递给ChildFunction,在此将计算结果,然后将最终响应从ChildFunction发送回ParentFunction。 您可以查看执行日志并按以下说明进行确认。

lambda调用函数_从另一个Lambda函数调用AWS Lambda函数

结论 (Conclusion)

In this article, I have explained how we can call or execute an AWS Lambda function from another lambda function within the same region. Using the AWS Lambda function, you can easily write serverless applications without having to worry about the infrastructure running behind it. Often, it becomes necessary that we might need to call different AWS Lambda functions from within another lambda due to the handling of complex business logic or something like that.

在本文中,我解释了如何从同一区域内的另一个lambda函数调用或执行AWS Lambda函数。 使用AWS Lambda函数,您可以轻松编写无服务器应用程序,而不必担心背后运行的基础架构。 通常,由于处理复杂的业务逻辑或类似的事情,我们可能有必要从另一个lambda中调用不同的AWS Lambda函数。

翻译自: https://www.sqlshack.com/calling-an-aws-lambda-function-from-another-lambda-function/

lambda调用函数