Step Function调用Lambda

本节我们将使用Step Function实现以下工作流:

传入一个Purchase Type事件,当它为PURCHASE时,调用purchase lambda处理;如果是REFUND,则调用refund lambda处理。

image-20220408155741896


创建两个lambda

进入Lambda页面,创建purchase_function函数:

image-20220408155404006

代码更新如下,并进行部署:

import json
import datetime

def lambda_handler(message, context):
    print(message)

    response = {}
    response['TransactionType']=message['TransactionType']
    response["TimeStamp"] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
    response["Message"] = "Hello from lambda land inside the ProcessPurchase function!"
    return response

再创建refund_function:

image-20220408155514770

更新代码如下,进行部署:

import json
import datetime

def lambda_handler(message, context):
    print(message)

    response = {}
    response['TransactionType']=message['TransactionType']
    response["TimeStamp"] = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
    response["Message"] = "Hello from lambda land inside the RefundPruchase function!"
    return response

将上面创建的两个Lambda的ARN复制下来,后面会使用到:

image-20220408155606218

形如以下格式:

arn:aws:lambda:us-east-1:145197526627:function:refund_function
arn:aws:lambda:us-east-1:145197526627:function:purchase_function

创建Step Functions

进入Step Functions服务,点击Create state machine:

image-20220408154856644

这里我们选择Write your workflow in code:

image-20220408155655024

Step Functions的JSON定义如下,将两处Resource替换为上一步获取到的Lambda ARN

{
  "Comment": "Transaction Process State Machine",
  "StartAt": "ProcessTransaction",
  "States": {
    "ProcessTransaction": {
      "Type": "Choice",
      "Choices": [
        {
          "Variable": "$.TransactionType",
          "StringEquals": "PURCHASE",
          "Next": "ProcessPurchase"
        },
        {
          "Variable": "$.TransactionType",
          "StringEquals": "REFUND",
          "Next": "ProcessRefund"
        }
      ]
    },
    "ProcessRefund": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:145197526627:function:refund_function",
      "End": true
    },
    "ProcessPurchase": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:145197526627:function:purchase_function",
      "End": true
    }
  }
}

更新State Machine的JSON定义后,Step Functions会实时渲染出对应的流程图:

image-20210322111758820

进入下一步,为Step Function命名,其他选项保持默认:

image-20220408155830304

下拉到底部,发现Step Functions智能地分析出了需要哪些权限(调用两个Lambda),并附加到Role中:

image-20220408155920188

点击创建。创建完成后进行测试,点击Start execution

image-20220408160021182

image-20220408160146580

测试Input如下:

{
    "TransactionType": "PURCHASE"
}

点击执行。在页面中能看到实时执行的结果,当执行完成后,可查看每个阶段的输入和输出:

image-20220408160740063

ProcessPurchas阶段,返回了Lambda的执行结果


新建Refund测试:

image-20220408160800392

将TransactionType更改为REFUND

image-20220408160838285

执行后,程序走的ProcessRefund分支,并能查看到对应Lambda的输出:

image-20220408160857438