以下是一个使用AWS SAM创建嵌套堆栈,并从根堆栈引用API网关的示例解决方案:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
MyApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Outputs:
ApiGatewayRestApiId:
Value: !Ref MyApiGateway
Export:
Name: MyApiGatewayRestApiId
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
ApiGatewayRestApiId:
Type: String
Description: ID of the API Gateway REST API
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs12.x
Events:
MyApiGatewayResource:
Type: Api
Properties:
RestApiId: !Ref ApiGatewayRestApiId
Path: /myapi
Method: GET
#!/bin/bash
# 部署根堆栈
aws cloudformation deploy \
--template-file root-stack.yaml \
--stack-name my-root-stack \
--capabilities CAPABILITY_IAM
#!/bin/bash
# 获取根堆栈输出的API Gateway REST API ID
apiGatewayRestApiId=$(aws cloudformation describe-stacks \
--stack-name my-root-stack \
--query 'Stacks[0].Outputs[?ExportName==`MyApiGatewayRestApiId`].OutputValue' \
--output text)
# 部署嵌套堆栈
aws cloudformation deploy \
--template-file nested-stack.yaml \
--stack-name my-nested-stack \
--parameter-overrides ApiGatewayRestApiId=$apiGatewayRestApiId \
--capabilities CAPABILITY_IAM
./deploy-root-stack.sh
./deploy-nested-stack.sh
这样,你就创建了一个包含根堆栈和嵌套堆栈的AWS SAM应用程序。嵌套堆栈通过根堆栈输出的API Gateway REST API ID来引用API网关。