Search code examples
rubyamazon-web-servicesamazon-cloudfrontamazon-route53

Using Ruby AWS SDK to create a Route53 alias to a Cloudfront distribution


I'm trying to automate creating an S3 backed CloudFront cached website served on a Route53 managed DNS.

I can create the S3 bucket with static website hosting and I know how to create a CloudFront distribution and a Route53 record, but when creating a Route53 record that is an alias to a CloudFront distribution one needs to provide a "hosted zone id" - which the Route53 interface has no problems finding, but I can't figure out how to use the AWS SDK to get that information.

Here's what I have:

def create_cf(domain)
  AWS::CloudFront.new.client.create_distribution distribution_config: createOptions(domain)
end

def create_r53(cfdistro, domain)
  target = {
    hosted_zone_id: cfdistro.id,
    dns_name: cfdistro.domain_name,
    evaluate_target_health: false
  }
  AWS::Route53.new.hosted_zones[myzone].rrsets.create "#{domain}.", 'A',
    alias_target: target
end

Unfortunately, the field id returned from create_distribution (or get_distribution) is what the CloudFront console shows as the ID of the distributions, but is not what Route53's console shows when I select the CloudFront distribution as an alias target. I actually couldn't figure out where to find the hosted zone ID in the CloudFront console!


Solution

  • Ok, that was silly - as documented in AWS Route53 documentation, all CloudFront distributions are hosted in the zone whose ID is Z2FDTNDATAQYW2.

    The "hosted zone ID" (I discovered after further reading) is the cryptographic identifier of a Route53 zone. The Route53 zone ids for public AWS domains (such as cloudfront.net) are published by Amazon in their documentation, exactly for this purpose.

    Do my code above should be:

    def create_r53(cfdistro, domain)
      target = {
        hosted_zone_id: 'Z2FDTNDATAQYW2',
        dns_name: cfdistro.domain_name,
        evaluate_target_health: false
      }
      AWS::Route53.new.hosted_zones[myzone].rrsets.create "#{domain}.", 'A',
        alias_target: target
    end