在定义单个 AWS::Serverless::Function 的 SAM 模板中指定多个 API 阶段和 Lambda 别名

cio*_*nzo 12 amazon-web-services aws-lambda aws-sam-cli aws-serverless aws-sam

我的目标是 尝试编写一个(单个)SAM 模板来获取由 Api 网关事件触发的 Lambda 函数。

我想要有多个 API 阶段(例如“dev”、“testing”、“prod”),并且希望每个阶段都映射到具有相同名称的 Lambda 别名。

我不想在每次部署时生成新的 lambda 版本,并且我喜欢手动设置每个 lambda 别名要使用的 lambda 版本。当然,“dev”别名意味着指向 $LATEST 代码版本。

我尝试了什么以及我得到了什么

我对经典的“hello_world”模板进行了如下修改。现在,当第一次部署(例如,“开发”)时,一切似乎都按预期工作。 但是,如果我尝试部署到“测试”阶段,则此新阶段的 API 会响应,而“开发”阶段的 API 将停止响应。

我缺少什么?

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  zzzz

  Sample SAM Template for zzzz

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Parameters:
  StageAliasName:
    Description: stage / alias name to be used in this deploy
    Type: String
    AllowedValues:
      - prod
      - stage
      - dev
      - v1
    Default: dev

Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageAliasName

  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.8
      AutoPublishAlias: !Ref StageAliasName
      FunctionName: zzz
      Environment:
        Variables:
          stage: !Ref StageAliasName
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            RestApiId: !Ref ApiGatewayApi
            Path: /hello
            Method: GET
#            Auth:
#              ApiKeyRequired: true



Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
#  HelloWorldApi:
#    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
#    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

Run Code Online (Sandbox Code Playgroud)

小智 0

I had the same question as you, and found this: https://jun711.github.io/aws/deploy-api-gateway-to-multiple-stage-when-aws-sam-replaces-previous-stages/. It looks like SAM replaces the previous stages.

这位小伙子做了一些手动步骤来使其工作。很高兴知道它可以工作,但是有点破坏了“基础设施即代码”,我想我将使用 ansible 为不同的环境模板化不同版本的模板,然后运行它。