在 template.yaml 中创建多个 API 网关实例时,如何控制在运行"sam local start-api"时模仿哪个网关?



>我创建了一个 SAM template.yaml 文件,其中包含两个 API 网关实例 - 一个用于生产,一个用于暂存。每个阶段都有自己的阶段,分别称为"生产"和"暂存",每个阶段都有自己的特定于环境的阶段变量。

我在本地构建的应用程序是使用 AWS SAM CLI 创建的,我一直在使用命令"sam local start-api"来运行 API 网关的本地实例来测试邮递员中的调用终端节点 - 这一直工作正常。不幸的是,我现在需要开始测试需要阶段变量的端点,并且我看不到任何方法可以告诉 SAM CLI 要模仿模板文件中的两个 API 网关实例中的哪一个。显然,我不希望它使用生产,因为它将具有连接到实时服务的数据。

我知道我可以创建一个包含两个阶段的 API 网关实例,因此,如果没有办法执行上述操作,有没有办法让 SAM 使用 API 网关实例中的特定阶段?下面是我的模板文件中的片段。

ApiProduction:
Type: AWS::Serverless::Api
Properties:
Name: service-layer-production-v1
StageName: Production
OpenApiVersion: 3.0.1
Auth:
ApiKeyRequired: true
Variables:
IS_STAGING: false
VARIABLE2: value-a
VARIABLE3: value-a
Models:
Error:
$schema: http://json-schema.org/draft-04/schema#
title: Error Schema
type: object
properties:
message:
type: string
Empty:
$schema: http://json-schema.org/draft-04/schema#
title: Empty Schema
type: object
properties:
message:
type: string
ApiStaging:
Type: AWS::Serverless::Api
Properties:
Name: service-layer-staging-vnull
StageName: Staging
OpenApiVersion: 3.0.1
Auth:
ApiKeyRequired: true
Variables:
IS_STAGING: true
VARIABLE2: value-b
VARIABLE3: value-b
Models:
Error:
$schema: http://json-schema.org/draft-04/schema#
title: Error Schema
type: object
properties:
message:
type: string
Empty:
$schema: http://json-schema.org/draft-04/schema#
title: Empty Schema
type: object
properties:
message:
type: string

如果条件 https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if,您可以使用云形成来实现这一点。

下面是一个快速示例:


# Set expected parameter to be passed to sam local
Parameters:
Stage:
Type: String
Default: staging
Description: Parameter for getting the deployment stage
# Create a condition based on the parameter
Conditions:
isStagingEnvironment: !Equals
- Ref: Stage
- staging
Resources:
MyFunction:
Type: "AWS::Serverless::Function"
Properties:
Events:
CatchAll:
Type: Api
Properties:
Method: GET
Path: /my-sample-function
# If condition to switch which API to use for this event while invoking the function
RestApiId: !If
- isStagingEnvironment
- !Ref ApiStaging
- !Ref ApiProduction

然后,您可以通过以下方式在本地运行您的 sam:

sam local start-api --parameter-overrides Stage=staging

如果每个 API 网关有多个阶段,则可以使用相同的技术。

最新更新