Dat*_*ray 11 amazon-web-services aws-cloudformation aws-api-gateway serverless-framework aws-sam
我想将我的 SAM 应用程序拆分为多个部分。
我想在根堆栈中创建一个 API ( AWS::Serverless::Api )。
我正在我的子堆栈中创建 lambda 函数,我想在其中提供从根堆栈到 API 事件的 API 引用。
这可行吗?我没有找到任何从根堆栈访问 API 到子堆栈的好例子?
我尝试使用以下模板 -
parenttemplateapi:
Type: AWS::Serverless::Application
Properties:
Location:
ApplicationId: arn:aws:serverlessrepo:us-east-1:account_id:applications/parent-template
SemanticVersion: 1.0.0
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python2.7
Events:
HelloWorld:
Type: Api
Properties:
Method: get
Path: /hello
RestApiId: !GetAtt parenttemplateapi.Outputs.ServerlessGW-restApiId
Run Code Online (Sandbox Code Playgroud)
当我尝试部署此模板时,出现以下错误 -
错误:无法为堆栈创建变更集:子模板,例如:Water ChangeSetCreateComplete 失败:Water 遇到终端故障状态状态:FAILED。原因:转换 AWS::Serverless-2016-10-31 失败:内部转换失败。
任何指示/建议?
我指的是以下链接 -
此处可以使用来自根堆栈的 API 网关 ID (AWS::ApiGateway::RestApi) 吗?
https://dev.to/grahamcox82/building-a-larger-serverless-application-part-3-modular-monorepos-3mon
这可以使用无服务器框架来实现吗?
这里需要注意的是,我不使用 AWS SAM,因为我只使用serverless.ymlServerlessFramework 文件来声明要部署的资源。
在我的ROOTAPI 中,我声明了我的子 lambda 所依赖的一系列输出,以便我的所有端点都可以具有相同的 Rest API ID。此输出声明嵌套resources在我的文件中的声明下serverless.yml,如下所示:
resources:
Resources:
...
stuff here that you may need
...
# API Gateway Cross Stack Reference Exports!!!!!
# Outputs that other services will depend on!!!
Outputs:
ApiGatewayRestApiId:
Value:
Ref: ApiGatewayRestApi
Export:
Name: ${self:custom.stage}-ApiGatewayRestApiId
ApiGatewayRestApiRootResourceId:
Value:
Fn::GetAtt:
- ApiGatewayRestApi
- RootResourceId
Export:
Name: ${self:custom.stage}-ApiGatewayRestApiRootResourceId
Run Code Online (Sandbox Code Playgroud)
实现此功能后,您需要在文件provider部分的子 lambda 中导入对此父 API 资源的引用serverless.yml。
# Cross-Stack Reference for sharing of API Gateway URI
# created with accounting-api
apiGateway:
restApiId: ${cf:ROOT_API_NAME_HERE-dev.ApiGatewayRestApiId}
#"Fn::ImportValue": ${self:custom.stage}-ApiGatewayRestApiId
restApiRootResourceId:
${cf:ROOT_API_NAME_HERE-dev.ApiGatewayRestApiRootResourceId}
#"Fn::ImportValue": ${self:custom.stage}-ApiGatewayRestApiRootResourceId
Run Code Online (Sandbox Code Playgroud)
您必须注意restApiId需要从CloudFormation父 API 的堆栈中导入的内容。您可以通过进入父 API 中的 CloudFormation 堆栈来查看输出;单击输出并restApiId根据需要找到您的值。
还有另一种方法允许您导入值,Fn::ImportValue您可以通过此处显示的示例进行查看:
https://github.com/serverless/examples/blob/master/aws-node-shared-gateway/users/serverless.yml
我在上面给你粘贴的代码中注释掉了这个方法,供你参考。