首页 > 解决方案 > 如何使用用 python 编写的单个 AWS Lambda 函数一次调用/触发不同的多个 AWS Step Functions?

问题描述

请观察以下 AWS Lambda 函数(在 python 代码中)以调用单个 AWS Step Function:

import boto3

def lambda_handler(event, context):

print("stating to invoke the AWS Step function.")

response = {"code":400, "message":""}

try :
     stepFunction = boto3.client('stepfunctions')
     response = stepFunction.start_execution(
            stateMachineARN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
             )
except Exception as e:
      response["message"] = f"failed to invoke the step function,{e}"

finally:
      print(response)
      return response

现在,我想使用上述单个 AWS Lambda 函数一次调用不同的多个 AWS Step 函数(串行和并行)。谁能帮我修改上面的代码?

标签: pythonamazon-web-servicesaws-lambdaboto3aws-step-functions

解决方案


这是基础知识,但请注意不要在另一个 lambda 函数中意外调用此函数,否则会陷入永久循环

def trigger_my_other_lambda(event, context):
    invoked_function_name = os.environ['INVOKED_FUNCTION_NAME']

    # this lambda function invokes another lambda function
    # invoke other lambda as many times as in tasks_list or other range
    for myarn in arnslist:
        '''pass data in form of dictionary; this shows up and must be parsed by the event argument of receiving lambda'''
        data = {"stateMachineARN" : myarn}
        # print(data)
        response = client.invoke(
            FunctionName=invoked_function_name,
            # InvocationType='RequestResponse', # synchornous - waits for response
            InvocationType='Event', # asynch - much faster - doesn't wait for response
            Payload=json.dumps(data)
        )

然后您现有的 lambda 将使用如下事件:

 stepFunction = boto3.client('stepfunctions')
 response = stepFunction.start_execution(
        stateMachineARN = event['stateMachineARN']
         )

推荐阅读