Home > OS >  AWS SAM two domains mapped to single function
AWS SAM two domains mapped to single function

Time:07-02

I have a requirement to configure two domains to single AWS SAM function. I already have that function running on a single custom domain, here is my code so far:

Resources:
  ApiCertificate:
    Type: AWS::CertificateManager::Certificate
    Properties:
      DomainName: !Sub abc-${StageName}.xyz.com
      ValidationMethod: DNS
  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageName
      EndpointConfiguration: REGIONAL
      Domain:
        DomainName: !Sub abc-${StageName}.xyz.com
        CertificateArn: !Ref ApiCertificate
        Route53:
          HostedZoneName: "xyz.com."
  loginFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/login.loginHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      
      Events:
        Api:
          Type: Api
          Properties:
            Path: /login
            Method: POST
            RestApiId: !Ref RestApi

Is there a way to configure another domain to the same function, which means, two different domains working for a same function.

CodePudding user response:

You have to declare a new block for AWS::Serverless::Api with your new domain and link that with another Events.

I have updated your code:

Resources:
  ApiCertificate:
    Type: AWS::CertificateManager::Certificate
    Properties:
      DomainName: !Sub abc-${StageName}.xyz.com
      ValidationMethod: DNS
  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageName
      EndpointConfiguration: REGIONAL
      Domain:
        DomainName: !Sub abc-${StageName}.xyz.com
        CertificateArn: !Ref ApiCertificate
        Route53:
          HostedZoneName: "xyz.com."
  SecondApiCertificate:
    Type: AWS::CertificateManager::Certificate
    Properties:
      DomainName: !Sub pqr-${StageName}.stu.com
      ValidationMethod: DNS
  SecondRestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref StageName
      EndpointConfiguration: REGIONAL
      Domain:
        DomainName: !Sub pqr-${StageName}.stu.com
        CertificateArn: !Ref SecondApiCertificate
        Route53:
          HostedZoneName: "stu.com."
  loginFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/login.loginHandler
      Runtime: nodejs16.x
      Architectures:
        - x86_64
      MemorySize: 128
      Timeout: 100
      
      Events:
        Api:
          Type: Api
          Properties:
            Path: /login
            Method: POST
            RestApiId: !Ref RestApi
        SecondApi:
          Type: Api
          Properties:
            Path: /login
            Method: POST
            RestApiId: !Ref SecondRestApit 

  • Related