Serverless – creating DNS entries for API Gateway

The following can be included in your serverless.yml file to create a sub-domain in Route53, and link it upto your API Gateway (HTTP) endpoint.

The following variables are required in your ‘custom’ block in the serverless.yml file;

  • certificate_arn – this is the ARN of your AWS Certificate Manager SSL certificate. For regional endpoints, this should be a cert created in the same region as your API Gateway.
  • domain_hosted_zone – the zone name of your domain name (eg. if your subdomain you want is abcd.myexample.com, the domain_hosted_zone will be example.com
  • domain_name – this is the complete sub-domain (eg. abcd.myexample.com)

Eg;

custom:
  domain_hosted_zone: 'example.com.'
  domain_name: 'abcd.example.com'
  certificate_arn: 'arn:aws:acm:ap-southeast-2:1233456:certificate/abc123'
resources:
  Resources:
    APIDomainName:
      Type: 'AWS::ApiGatewayV2::DomainName'
      Properties:
        DomainNameConfigurations:
          - CertificateArn: ${self:custom.certificate_arn}
        DomainName: ${self:custom.domain_name}

    APIDomainMapping:
      Type: 'AWS::ApiGatewayV2::ApiMapping'
      Properties:
        ApiId: !Ref HttpApi
        DomainName: !Ref APIDomainName
        Stage: !Ref HttpApiStage
      DependsOn: [ APIDomainName ]

    APIDomain:
      Type: AWS::Route53::RecordSetGroup
      Properties:
        HostedZoneName: ${self:custom.domain_hosted_zone}
        RecordSets:
          - Name: !Ref APIDomainName
            Type: A
            AliasTarget:
              DNSName: !GetAtt APIDomainName.RegionalDomainName
              HostedZoneId: !GetAtt APIDomainName.RegionalHostedZoneId

Ref; https://theburningmonk.com/cloudformation-ref-and-getatt-cheatsheet/

Leave a Reply