以下是使用AWS SAM创建/导出API Gateway资源并在另一个堆栈中导入的解决方案,包含代码示例。
在第一个堆栈的template.yaml文件中,使用AWS::Serverless::Api资源创建API Gateway资源,并将其导出为CloudFormation输出。
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
DefinitionBody:
swagger: "2.0"
info:
version: "1.0"
title: "My API"
paths:
/hello:
get:
responses:
"200":
description: "OK"
schema:
type: string
Outputs:
ApiGatewayRestApiId:
Value: !Ref MyApi
Export:
Name: MyApi-Id
ApiGatewayStageName:
Value: Prod
Export:
Name: MyApi-StageName
在第二个堆栈的template.yaml文件中,使用AWS::CloudFormation::ImportValue函数导入第一个堆栈中导出的API Gateway资源。
Resources:
LambdaFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs14.x
Events:
ApiEvent:
Type: Api
Properties:
Path: /hello
Method: get
RestApiId: !ImportValue MyApi-Id
RestApiRootResourceId: !ImportValue MyApi-Id/RootResourceId
StageName: !ImportValue MyApi-StageName
在上述示例中,我们使用了AWS::CloudFormation::ImportValue函数分别导入了API Gateway的资源ID和阶段名称。这样,我们就可以在第二个堆栈中创建Lambda函数,并将其与第一个堆栈中创建的API Gateway资源关联起来。
注意:确保在部署第二个堆栈之前,先部署第一个堆栈,以确保API Gateway资源已经创建并导出。
希望以上解决方案对您有所帮助!