Search code examples
amazon-web-servicesterraformamazon-cloudfrontamazon-route53

How to create different DNS records in Route53 for each environment(stage, prod) for a single domain?


So I've got one domain: example.com and I want to setup a stage and prod environment. I'm having trouble understanding how to have different DNS records for a single cloudfront distribution, for example: prod1.example.com and stag1.example.com

I was going to try to use separate state files to manage each environment, however this would cause the cloudfront distribution to be re-created and likely fail since there will already be a distribution existing with the domain I'm trying to use.

If I use the same state file, then I would need to create two distributions, pointing at separate buckets, but this seems to create issues since I have environment specific variables and it just doesn't seem to make any sense.

Perhaps I need to create a separate project just for managing the cloudfront aspect and another project for managing the other resources? Currently I'm doing it all in one project.


Solution

  • You can use separate state files for the different environments and that would be the best solution. This way you can have separate CloudFront distribution per environment, with everything else also separated.

    There is a data source for the route 53 zone (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/route53_zone):

    data "aws_route53_zone" "zone" {
      name = "..."
    }
    

    Then you can add A records to the CloudFront distributions:

    resource "aws_route53_record" "www" {
      zone_id = "${data.aws_route53_zone.zone.zone_id}"
      name    = "${var.prefix}.${data.aws_route53_zone.zone.name}"
      type    = "A"
    
      alias {
        name                   = "${aws_cloudfront_distribution.s3_distribution.domain_name}"
        zone_id                = "Z2FDTNDATAQYW2"
        evaluate_target_health = true
      }
    }
    

    This way as long as the prefixes (prod1, stage1) don't clash you can deploy multiple states concurrently.