Mehdi
Mehdi

Reputation: 775

Get dnsName and hostedZoneId from HttpApi in the same stack

Using aws cdk, I am creating an apigatewayv2.HttpApi backed by lambda functions.

I would like to setup a custom domain (apiCustomDomain) name for this created API, however I can't seem to find a way to retrieve the dnsName and hostedZoneId from the created API to create an ARecord.

    import * as apigateway2 from '@aws-cdk/aws-apigatewayv2';

    const apiCustomDomain = new apigateway2.DomainName(this, 'api-custom-domain', {
        domainName: subDomainName,
        certificate: certificate
    });

    const api = new apigateway2.HttpApi(this, 'my-api', {
        apiName: 'my-api',
        defaultDomainMapping: {
            domainName: apiCustomDomain
        },
        createDefaultStage: true,
        disableExecuteApiEndpoint: false,
        defaultAuthorizer: new HttpIamAuthorizer()
    });

    new route53.ARecord(this, 'a-api-record', {
        zone: hostedZone,
        recordName: subDomainName,
        target: route53.RecordTarget.fromAlias({
            bind(record: IRecordSet, zone?: IHostedZone): AliasRecordTargetConfig {
                return {
                     dnsName: api.?????, // what to put here 
                     hostedZoneId: api.????? // what to put here
                }
            }
        })
    });

Now in the v1 of apigateway, it was straightforward, we would get those values from the domainName property of the api, something like:

   dnsName = api.domainName!.domainNameAliasDomainName
   hostedZoneId = api.domainName!.domainNameAliasHostedZoneId

But I can't find the same for the apigatewayv2 library.

Upvotes: 0

Views: 354

Answers (1)

fedonev
fedonev

Reputation: 25809

Pass the existing Hosted Zone retrieved using fromLookup and a ApiGatewayv2DomainProperties target from the Route53 targets module to the ARecord.

const zone = route53.HostedZone.fromLookup(this, 'HostedZone', {
  domainName: domain,
});

new route53.ARecord(this, 'AliasRecord', {
  recordName: subdomain,
  zone,
  target: route53.RecordTarget.fromAlias(
    new targets.ApiGatewayv2DomainProperties(
      apiCustomDomain.regionalDomainName,
      apiCustomDomain.regionalHostedZoneId
    )
  ),
});

Upvotes: 1

Related Questions