Malvineous
Malvineous

Reputation: 27330

How to add a Route53 alias to an existing Route53 entry?

I have a DNS entry already in Route 53. In my CDK stack, I want to set up an alias (effectively a CNAME), so I have a new DNS entry pointing to the existing one. For example, I want to make new.example.com point to existing.example.com, where example.com is hosted in Route 53 and existing is already set up and working.

Through the AWS console I would just create a new A or CNAME record for new.example.com and set it as an alias of existing.example.com and it would be fine, so I am trying to replicate this in CDK.

In the CDK docs, it says I can do this:

declare const zone: route53.HostedZone;
declare const record: route53.ARecord;
new route53.ARecord(this, 'AliasRecord', {
  zone,
  target: route53.RecordTarget.fromAlias(new targets.Route53RecordTarget(record)),
});

However, the docs don't say how to populate the record variable.

If I look at the route53.ARecord docs, there doesn't appear to be a way to look up an existing record.

The closest I could find is using one of the other RecordSet.fromXXX() functions instead of fromAlias, however there doesn't appear to be one that can look up host names:

...
target: cdkRoute53.RecordTarget.fromValues('target.example.com'), // doesn't work

Unfortunately, RecordTarget.fromValues() only accepts an IP address. If you put a hostname in, it tells you:

Invalid Resource Record: 'FATAL problem: ARRDATAIllegalIPv4Address (Value is not a valid IPv4 address) encountered with 'target.example.com'

So it looks like I can only create the alias if I also created the target records in the same stack - there doesn't appear to be a way to load an existing record, so you can pass it in as the target for the new alias.

What am I missing?

Upvotes: 0

Views: 897

Answers (1)

Malvineous
Malvineous

Reputation: 27330

I found a workaround in the meantime thanks to this answer. Since then they added the functionality that was missing, but it looks like they didn't provide lookups so that workaround still applies.

The solution is to provide a bind() function instead that provides the necessary information:

const route53entry = new cdkRoute53.ARecord(this, 'dns', {
  recordName: 'new.example.com',
  zone: hostedZone,
  target: cdkRoute53.RecordTarget.fromAlias({
    bind: () => ({
      dnsName: 'existing.example.com',
      hostedZoneId: hostedZone.hostedZoneId,
    }),
  }),
});

Upvotes: 1

Related Questions