Kwhitejr
Kwhitejr

Reputation: 2306

SAM Template: multiple microservice lambdas sharing a single AWS::ApiGateway::DomainName

My goal is allow several independent lambda resources (microservices) to share a common custom domain for test environment. Using the below template, deploying microservice #1 went off without issue. However, when deploying microservice #2, CloudFormation fails and rolls back because the domain name is assigned to microservice #1.

Surely it must be possible to share a common custom domain among several microservices with unique paths?

Service #1 template.yaml

Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Sub ${apiGatewayStageName}
      DefinitionBody:
        swagger: "2.0"
        info:
          title: !Sub ${functionName}
        paths:
          "/service_one":
            post:
              responses: {}
              x-amazon-apigateway-integration:
                uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${functionName}:live/invocations"
                httpMethod: POST
                type: aws_proxy

  ApiGatewayCustomDomainName:
    Type: AWS::ApiGateway::DomainName
    Properties:
      CertificateArn: !Sub "arn:aws:acm:${AWS::Region}:${AWS::AccountId}:certificate/${apiGatewayCDNCertificateId}"
      DomainName: !Sub "${envName}.${apiGatewayCustomDomainNameSuffix}"
    DependsOn:
      - "LogsSubscriptionFilter"
      - "ApiGatewayApi"

  ApiGatewayBasePathMapping:
    Type: AWS::ApiGateway::BasePathMapping
    Properties:
      DomainName: !Ref ApiGatewayCustomDomainName
      RestApiId: !Ref ApiGatewayApi
      Stage: !Ref apiGatewayStageName
    DependsOn: "ApiGatewayCustomDomainName"

The Service #2 template is the same, except with a different path (.e.g. /service_two.

Upvotes: 3

Views: 2956

Answers (1)

Kwhitejr
Kwhitejr

Reputation: 2306

Worked with AWS support to get to the bottom of this one. In its current form (May 2018), if you want separate SAM templates for each lambda for deployment reasons, but have a shared API Gateway resource for those lambdas, then you must have a separate dedicated API Gateway SAM template. Additionally, the Events parameter in AWS::Serverless::Function must be excluded in favor of paths definitions in AWS::Serverless::Api.

Lastly, the AWS::Serverless::Function(s) must be exported under Output and then imported by the AWS::Serverless::Api resource.

Upvotes: 3

Related Questions