AWS API Gateway与Step Function

7
我希望能提供一个整合AWS API Gateway和Step Function的示例。我已经阅读了这篇教程Creating a Step Functions API Using API Gateway,但是该教程需要我以以下格式发送请求:
{    
"input": "{}",    
"name": "PostmanExecution",    
"stateMachineArn": "arn:aws:states:us-east-1:123456789012:stateMachine:Custom" 
}

我希望能够在API Gateway中发送普通请求并配置这个stateMachineArn,这样客户端就不需要发送它。

2个回答

20

创建 API 网关资源和方法。然后在“方法执行”设置中,在集成请求中使用以下设置:

  • 集成类型:AWS 服务
  • AWS 区域:您的区域
  • AWS 服务:Step Functions
  • AWS 子域:如果您有,请填写子域 - 我将其留空
  • HTTP 方法:POST
  • Action:StartExecution
  • 执行角色:需要具有 StepFunction start execute 策略的角色,例如 arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess
  • Credentials cache:我将其保留为默认设置
  • 内容处理:透传

然后是魔法。在更深处,下面是 Body Mapping Templates:

  • 请求正文透传:永不
  • 添加映射模板:application/json

在模板文本框中更深处:

#set($input = $input.json('$'))
{
   "input": "$util.escapeJavaScript($input)",
   "stateMachineArn": "arn:aws:states:eu-west-1:123456789012:stateMachine:yourStepFunctionName"
}

这将把POST到API Gateway的json负载传递给Step Function。

省略执行名称,以便每次调用API Gateway都创建一个新的执行。


有什么想法将您的 resourceTemplate 添加到 CloudFormation 模板中吗? - quadroid
@控制台 我刚刚发布了一个使用CloudFormation的可行解决方案。 - Julio Villane
1
我想动态地使用区域和帐户 ID 来形成 stateMachineArn。我可以从 $context.accountId 获取帐户 ID,但是找不到任何可以提供当前区域名称的东西。在我的模板中,stateMachineArn 现在看起来像这样:"arn:aws:states:us-east-1:$context.accountId:stateMachine:AbcStateMachine"。有什么办法可以动态获取当前区域吗? - rockyPeoplesChamp
1
你知道如何向输入添加额外参数吗?例如,Cognito用户的电子邮件:($context.authorizer.claims.email) 它必须在“input”中,因为这是传递给Lambda的内容。不确定该如何实现。 - Jack Marchetti

3

我使用API Gateway暴露了2个端点,一个用于启动执行,另一个用于检查执行状态。

这些操作不需要使用lambda,也不需要通过参数指示步骤函数arn。

解决方案的CloudFormation 模板如下:

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: >
  The turtle calculator, a dummy slow calculator for comprehensive code example
Parameters:
  OpenAPIS3File:
    Description: '"openapi.yaml" file location'
    Default: ./openapi.yaml
    Type: String

Resources:
  Workflow:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      StateMachineName: !Sub ${AWS::StackName}-state-machine
      RoleArn: !GetAtt StateExecutionRole.Arn
      DefinitionString: !Sub |
        {
          ...
        }

  Api:
    Type: AWS::Serverless::Api
    Properties:
      StageName: random-workflow
      Name: !Sub ${AWS::StackName}-api
      DefinitionBody:
        'Fn::Transform':
          Name: AWS::Include
          Parameters:
            Location: !Ref OpenAPIS3File

而 OpenAPI 配置如下:

openapi: 3.0.1
info:
  title: Api Mocker
  description: Automated testing application for TGR
  contact:
    name: Patagonia-IT
    url: http://www.patagonia-it.com
    email: contacto@patagonia-it.com
  license:
    name: Apache 2.0
    url: https://www.apache.org/licenses/LICENSE-2.0.html
  version: 1.0.0

x-amazon-apigateway-request-validators:
  params:
    validateRequestParameters: true
    validateRequestBody: false

x-amazon-apigateway-request-validator: params

paths:
  /workflow:
    post:
      x-amazon-apigateway-integration:
        credentials:
          Fn::GetAtt: [ ApiGatewayStepFunctionsRole, Arn ]
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
        httpMethod: POST
        type: aws
        responses:
          default:
            statusCode: 200
            responseTemplates:
              application/json: |
                '{ "executionId": "$input.json('executionArn').split(':').get(7) }'
        requestTemplates:
          application/json:
            Fn::Sub: |-
              {
                "input": "$util.escapeJavaScript($input.json('$'))",
                "name": "$context.requestId",
                "stateMachineArn": "${Workflow}"
              }
      summary: Start workflow instance
      responses:
        200:
          $ref: '#/components/responses/200Execution'
        403:
          $ref: '#/components/responses/Error'
  /workflow/{executionId}:
    get:
      x-amazon-apigateway-integration:
        credentials:
          Fn::GetAtt: [ ApiGatewayStepFunctionsRole, Arn ]
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/DescribeExecution
        httpMethod: POST
        type: aws
        responses:
          default:
            statusCode: 200
            responseTemplates:
              application/json: |-
                #set ($status = $input.json('status'))
                {
                #if($status == '"SUCCEEDED"')
                  "output": $util.parseJson($input.json('output')),
                #end
                  "status": $status
                }
        requestTemplates:
          application/json:
            Fn::Sub: |-
              {
                "executionArn": "arn:aws:states:${AWS::Region}:${AWS::AccountId}:execution:${Workflow.Name}:$input.params().path.get('executionId')"
              }
      summary: Workflow execution status
      responses:
        200:
          $ref: '#/components/responses/200ExecutionDetails'

我在 Github 上提交了一个可工作的示例,网址为 https://github.com/jvillane/aws-sam-step-functions-lambda


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接