使用无服务器将多个服务部署到具有共享路径的Apigateway

时间:2019-02-14 16:53:57

标签: aws-api-gateway serverless aws-serverless

documentation addresses shared paths

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 而不是将其创建为第一个服务中函数定义的副作用。但是我该怎么做呢?而且会不会与函数定义冲突?

1 个答案:

答案 0 :(得分:0)

经过一番挣扎之后,我遇到了以下问题:第一次服务应该 定义资源路径,但其余网关定义保持隐式。并且应该输出相关的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前缀定义路径,而不会发生冲突。