Terraform: Route53, LB and CDN interdependency

Viewed 402

My team uses Terraform to deploy the necessary infrastructure. Currently, our stack is composed of: AutoScalingGroup fronted by a Load-Balancer, and a Route53 DNS record that points to this LB;

We would like to extend the stack to include a Cloudfront distribution that points to the LB, and make the Route53 DNS record point to the CDN.

I would like to be able to:

  • spin up Cloudfront and change the DNS record to point to the CDN, without causing any downtime;
  • tear down the CDN, change the DNS to point to the load-balancer, without causing any downtime;

The current configuration is as follows:

resource "aws_lb" "alb" {
  name                       = "${var.alb-name}"
  ...
}
resource "aws_cloudfront_distribution" "cdn" {
  count = "${var.use_cloudfront != "false" ? 1 : 0}"
  ...
}
resource "aws_route53_record" "www" {
  count = "${var.domain-name != "" ? 1 : 0}"

  depends_on = ["aws_lb.alb", "aws_cloudfront_distribution.cdn"]  

  zone_id = "${data.aws_route53_zone.primary.zone_id}"
  name    = "${var.domain-name}"
  type    = "A"

  alias = {
    // we use concat because 'count' makes the response of the resource a list. 
    // link to similar issue: https://stackoverflow.com/questions/45654774/terraform-conditional-resource
    name                   = "${var.use_cloudfront == "true" ? element(concat(aws_cloudfront_distribution.cdn.*.domain_name, list("")), 0) : aws_lb.alb.dns_name}"    
    zone_id                = "${var.use_cloudfront == "true" ? element(concat(aws_cloudfront_distribution.cdn.*.hosted_zone_id, list("")), 0) : aws_lb.alb.zone_id}"
    evaluate_target_health = true
  }
}

The current behavior is as follows:

  • the spin-up of the CDN, followed by re-routing the DNS record to point to the CDN, does not lead to any downtime;
  • the tear-down of the CDN, followed by re-routing the DNS record to the load-balancer, does cause downtime;

I am aware that the depends_on = ["aws_lb.alb", "aws_cloudfront_distribution.cdn"] on the Route53 record might not be the best choice to create the desired behavior. However, I am not sure how to reach the desired behavior using terraform.

I am wondering if anyone has any suggestions to reach the desired behavior. Let me know if the provided information is insufficient. Thank you for your help, it is appreciated!

0 Answers
Related