使用 Cloudformation 的 AWS 无服务器 API 阶段 "dev already exists"

Stage "dev already exists" for AWS Serverless API with Cloudformation

我需要通过 AWS::Serverless::Api 自定义 default Stage generated

堆栈创建出现错误“dev 已经存在”。

我的模板代码:

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: my-service
      StageName: dev

  MyApiDeployment:
    Type: AWS::ApiGateway::Deployment
    Properties:
      RestApiId: !Ref MyApi
      StageName: dev

  MyStage:
    Type: AWS::ApiGateway::Stage
    DependsOn: MyApiDeployment
    Properties:
      StageName: dev
      RestApiId: !Ref MyApi
      DeploymentId: !Ref MyApiDeployment

  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: MyAssembly::MyNamespace::MyHandler
      Runtime: dotnetcore2.1
      Events:
        ApiRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: ANY

输出错误:

MyStage                                  CREATE_FAILED                            dev already exists

目标是从同一模板文件中的另一个资源引用 Stage。

  MyMapping:
    Type: AWS::ApiGateway::BasePathMapping
    Properties:
      BasePath: my-path
      RestApiId: !Ref MyApi
      Stage: !Ref MyStage

发生错误是因为您试图两次创建相同的资源。通过在 AWS::Serverless::Api 资源 [MyApi] 上指定阶段名称,您将创建该阶段。

per the documentation一样,不必为API网关指定阶段;但是对于 SAM。尝试删除舞台资源 [MyStage] 并重新部署。

Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: my-service
      StageName: dev

  MyStage:
    Type: AWS::ApiGateway::Stage
    DependsOn: MyApiDeployment
    Properties:
      StageName: dev
      RestApiId: !Ref MyApi
      DeploymentId: !Ref MyApiDeployment

我在这个论坛上找到了解决方案:https://github.com/awslabs/serverless-application-model/issues/192#issuecomment-520893111

阶段属性中的引用必须带!Ref MyApi.Stage不能带名称按字符串.

正确代码:

  MyMapping:
    Type: AWS::ApiGateway::BasePathMapping
    Properties:
      BasePath: my-path
      RestApiId: !Ref MyApi
      Stage: !Ref MyApi.Stage