上周末我玩了 AWS Step Functions!为了可维护性和进化性,我想重构一个我已经编码的 Lambda 函数。

https://twitter.com/johanrin/status/1386327733408514052

在使用 AWS 无服务器应用程序模型 (AWS SAM) 重构并在 AWS 上部署我的工作流后,我想通过一个简单的端点从 AWS 外部调用它。

因为我在网上花了 2 多分钟才弄明白怎么弄,我觉得有必要有这篇博文来帮助你。

开始吧!

概述

在这篇文章中,我们将在 API 网关后面部署一个基本的 Step Functions 工作流程,一个简单的 POST 请求将触发,如下所示:

架构概述

而且因为我们使用 AWS SAM,我们只需要几行 YAML。而已!

亚马逊API网关

template.yaml中,我们先定义一下我们的API网关资源:

Resources:
  HelloWorldApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev

在这里,我们创建了一个名为HelloWorldApi的新Amazon API Gateway,其中包含最基本的信息:舞台名称。

AWS Step Functions 状态机

现在,让我们在状态机中引用我们的 API 网关!为此,请创建如下定义的Events部分:

  HelloWorldStateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      DefinitionUri: statemachine/hello_world.asl.json
      DefinitionSubstitutions:
        HelloWorldFunctionArn: !GetAtt HelloWorldFunction.Arn
      Events:
        HelloWorldApiEvent:
          Type: Api
          Properties:
            Method: post
            Path: /
            RestApiId: 
              Ref: HelloWorldApi
      Policies:
        - LambdaInvokePolicy:
            FunctionName: !Ref HelloWorldFunction

Events部分包含我们状态机的所有触发器。在我们的例子中,我们定义了一个名为HelloWorldApiEvent的 API 事件,它引用了我们之前创建的 API 网关,并附加了一个 POST 请求。

输出

为方便起见,让我们定义一个额外的输出来了解使用哪个端点来触发我们的工作流程:

Outputs:
  HelloWorldApi:
    Description: "API Gateway endpoint URL to call Hello World State Machine"
    Value: !Sub "https://${HelloWorldApi}.execute-api.${AWS::Region}.amazonaws.com/dev/"

我们现在都准备好部署我们的工作了。让我们在下一节中看看如何!

使用 AWS SAM 进行部署

现在我们完成了template.yaml的编辑,它通常看起来像这样:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-step-functions-api-tutorial

  Sample SAM Template for sam-step-functions-api-tutorial

Resources:
  HelloWorldApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev

  HelloWorldStateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      DefinitionUri: statemachine/hello_world.asl.json
      DefinitionSubstitutions:
        HelloWorldFunctionArn: !GetAtt HelloWorldFunction.Arn
      Events:
        HelloWorldApiEvent:
          Type: Api
          Properties:
            Method: post
            Path: /
            RestApiId: 
              Ref: HelloWorldApi
      Policies:
        - LambdaInvokePolicy:
            FunctionName: !Ref HelloWorldFunction

  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs14.x

Outputs:
  HelloWorldApi:
    Description: "API Gateway endpoint URL to call Hello World State Machine"
    Value: !Sub "https://${HelloWorldApi}.execute-api.${AWS::Region}.amazonaws.com/dev/"
  HelloWorldStateMachineArn:
    Description: "Hello World state machine ARN"
    Value: !Ref HelloWorldStateMachine
  HelloWorldStateMachineRole:
    Description: "IAM Role created for Hello World state machine based on the specified SAM Policy Templates"
    Value: !GetAtt HelloWorldStateMachineRole.Arn

让我们首先使用sam build命令构建我们的代码:

C:\sam-step-functions-api-tutorial>sam build
Building codeuri: C:\sam-step-functions-api-tutorial\functions\hello-world runtime: nodejs14.x metadata: {} functions: ['HelloWorldFunction']     
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts  : .aws-sam\build
Built Template   : .aws-sam\build\template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided

之后,让我们使用sam deploy -g命令和以下选项部署我们的工作:

C:\sam-step-functions-api-tutorial>sam deploy -g

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Not found

        Setting default arguments for 'sam deploy'
        ========================================= 
        Stack Name [sam-app]: sam-step-functions-api-tutorial
        AWS Region [us-east-1]: eu-west-1
        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
        Confirm changes before deploy [y/N]: 
        #SAM needs permission to be able to create roles to connect to the resources in your template
        Allow SAM CLI IAM role creation [Y/n]:
        Save arguments to configuration file [Y/n]: 
        SAM configuration file [samconfig.toml]: 
        SAM configuration environment [default]: 

        Looking for resources needed for deployment: Not found.
        Creating the required resources...

几分钟后,您将获得类似于以下输出的内容:


CloudFormation outputs from deployed stack
------------------------------------------------------------------------------------------------------------------------------------------------------------------   
Outputs
------------------------------------------------------------------------------------------------------------------------------------------------------------------   
Key                 HelloWorldStateMachineArn
Description         Hello World state machine ARN
Value               arn:aws:states:eu-west-1:717193739363:stateMachine:HelloWorldStateMachine-Ppeu4ioPCz1e

Key                 HelloWorldStateMachineRole
Description         IAM Role created for Hello World state machine based on the specified SAM Policy Templates
Value               arn:aws:iam::717193739363:role/sam-step-functions-api-tu-HelloWorldStateMachineRo-H8VZV35HFQB9

Key                 HelloWorldApi
Description         API Gateway endpoint URL to call Hello World State Machine
Value               https://sn46ephbv2.execute-api.eu-west-1.amazonaws.com/dev/
------------------------------------------------------------------------------------------------------------------------------------------------------------------   

Successfully created/updated stack - sam-step-functions-api-tutorial in eu-west-1

我们的工作现已部署在 AWS 上并准备好触发!

例如,使用邮递员:

邮递员

以及 AWS 中的相关结果:

工作流触发

结论

您使用 AWS SAM 将 API 网关附加到 Step Functions 工作流程! 🎉🎉

我们只需要几行 YAML 就可以组合这些服务。很方便!

您可以在此处找到包含完整代码的 GitHub 存储库:https://github.com/johanrin/sam-step-functions-api-tutorial

对我来说就是这样,希望你学到了一些东西!如果您有任何问题,在 Twitter 上找到我并随时问我任何问题🙏

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐