首页 > 解决方案 > 使用无服务器将多个服务部署到具有共享路径的 Apigateway

问题描述

文档地址共享路径

service: service-b
provider:
  apiGateway:
    restApiId: xxxxxxxxxx
    restApiRootResourceId: xxxxxxxxxx
    restApiResources:
      /reports: xxxxxxxxxx

functions:
  ...

但是,如何引用资源的 ID(即路径)?在第一项服务中,我有:

  Outputs:
    apiGatewayRestApiId:
      Value:
        Ref: ApiGatewayRestApi
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-restApiId
    apiGatewayRestApiRootResourceId:
      Value:
         Fn::GetAtt:
          - ApiGatewayRestApi
          - RootResourceId
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-rootResourceId
    apiGatewayResourceReports:
      Value: !Ref ApiGatewayResource/reports
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-reportPath

前两个工作,可以FN::ImportValue在第二个服务中引用。但是,第三个不起作用。我认为问题在于我必须显式创建资源ApiGatewayResource/reports ,而不是将其创建为第一个服务中函数定义的副作用。但是我该怎么做呢?它不会与函数定义冲突吗?

标签: aws-api-gatewayserverlessaws-serverless

解决方案


经过一番挣扎,我想到了以下几点:第一个服务应该定义资源路径,但保留网关定义的其余部分。它应该输出相关的ID:

provider:
  apiGateway:
    restApiResources:
      /reports: !Ref ReportPath

...
resources:
  Resources:
    ReportPath:
      Type: AWS::ApiGateway::Resource
      Properties:
        RestApiId: !Ref ApiGatewayRestApi
        ParentId:
          Fn::GetAtt: [ ApiGatewayRestApi, RootResourceId ]
        PathPart: 'reports'

  Outputs:
    apiGatewayRestApiId:
      Value:
        Ref: ApiGatewayRestApi
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-restApiId
    apiGatewayRestApiRootResourceId:
      Value:
         Fn::GetAtt:
          - ApiGatewayRestApi
          - RootResourceId
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-rootResourceId
    apiGatewayResourceReports:
      Value: !Ref ReportPath
      Export:
        Name: ${self:service}-${opt:stage, 'dev'}-apiGateway-reportPath

第二个服务可以引用所有三个 id:

provider:
  apiGateway:
    restApiId:
      'Fn::ImportValue': crane-mg-reports-${opt:stage, 'dev'}-apiGateway-restApiId
    restApiRootResourceId:
      'Fn::ImportValue': crane-mg-reports-${opt:stage, 'dev'}-apiGateway-rootResourceId
    restApiResources:
      /reports:
        'Fn::ImportValue': crane-mg-reports-${opt:stage, 'dev'}-apiGateway-reportPath

在这两种情况下,函数定义都可以使用 /reports 前缀定义路径而不会发生冲突。


推荐阅读