AWS 无服务器 API 与云形成的阶段"dev already exists"



我需要自定义AWS::Serverless::Api生成的默认阶段。

堆栈创建得到错误">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

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

Stage属性中的引用必须使用!Ref MyApi.Stage而不是使用字符串命名。

正确代码:

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

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

根据文件,不必为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

最新更新