rzlvmp
rzlvmp

Reputation: 9422

How to set Cloudfront cache behavior dynamically in terraform?

Let's suppose that I have a variable:

variable "is_cache_disabled" {
  type = bool
}

And I want to change behavior depending on this variable.

Two possible choices are:

resource "aws_cloudfront_distribution" "cloudfront_distribution" {
  ...
  default_cache_behavior {
    some_parameter_1 = some_value1
    some_parameter_2 = some_value2

    default_ttl = 86400
    max_ttl     = 86400
    min_ttl     = 3600
    forwarded_values {
      cookies {
        forward = "none"
      }
      query_string = true
    }
  }
}

and when cache is disabled (is_cache_disabled = true), it should be set as disabled ↓

data "aws_cloudfront_cache_policy" "cache_disabled" {
    name = "Managed-CachingDisabled"
}

resource "aws_cloudfront_distribution" "cloudfront_distribution" {
  ...
  default_cache_behavior {
    some_parameter_1 = some_value1
    some_parameter_2 = some_value2

    cache_policy_id = data.aws_cloudfront_cache_policy.cache_disabled.id
  }
}

As you can see single parameter cache_policy_id should be replaced with internal block forwarded_values and extra TTL keys in default_cache_behavior depending on variable. Probably default_cache_behavior should be dynamic, but I still can't figure out how to replace multiple keys and internal block using dynamic construction?

Upvotes: 0

Views: 528

Answers (1)

rzlvmp
rzlvmp

Reputation: 9422

Okay, here is my ugly way:

variable "is_cache_disabled" {
  type = bool
}

data "aws_cloudfront_cache_policy" "cache_disabled" {
    name = "Managed-CachingDisabled"
}

resource "aws_cloudfront_distribution" "cloudfront_distribution" {
  ...
  dynamic "default_cache_behavior" {
    for_each = var.is_cache_disabled ? {
      cache_disabled = {
        cache_policy_id = data.aws_cloudfront_cache_policy.cache_disabled.id
      }
    } : {
      cache_enabled = {
        default_ttl = 86400
        max_ttl     = 86400
        min_ttl     = 3600
      }
    }

    content {
      some_parameter_1 = some_value1
      some_parameter_2 = some_value2

      cache_policy_id = lookup(default_cache_behavior.value, "cache_policy_id", null)
      default_ttl     = lookup(default_cache_behavior.value, "default_ttl", null)
      max_ttl         = lookup(default_cache_behavior.value, "max_ttl", null)
      min_ttl         = lookup(default_cache_behavior.value, "min_ttl", null)
      dynamic "forwarded_values" {
        for_each = default_cache_behavior.key == "cache_enabled" ? [1] : []
        content {
          query_string = true
          cookies {
            forward = "none"
          }
        }
      }
    }
  }
}

At first sight looks like it works, but not easy readable

Upvotes: 0

Related Questions