A repository of bitesize articles, tips & tricks
(in both English and French) curated by Mirego’s team.

Using CloudFront’s managed policies in Terraform

While configuring a new AWS CloudFront distribution for a project, I wanted to take advantage of CloudFront’s managed policies (instead of creating my own).

Here’s a simplified version of the distribution I’m managing:

resource "aws_cloudfront_distribution" "cdn_webapp_distribution" {
  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "Origin-Webapp-Dev"
  }
}

Now, if I want to use a managed policy for both the cache policy and the origin request policy, I could hardcode the ID provided by AWS (for both cache policies and origin request policies):

resource "aws_cloudfront_distribution" "cdn_webapp_distribution" {
  default_cache_behavior {
    allowed_methods          = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods           = ["GET", "HEAD"]
    target_origin_id         = "Origin-Webapp-Dev"
    cache_policy_id          = "658327ea-f89d-4fab-a63d-7e88639e58f6"
    origin_request_policy_id = "216adef6-5c7f-47e4-b989-5492eafa07d3"
  }
}

But that’s not great, right? What we can do instead is fetching those managed policies as data sources (using their name) and then use them in our distribution resource:

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

data "aws_cloudfront_origin_request_policy" "cdn_managed_all_viewer_origin_request_policy" {
  name = "Managed-AllViewer"
}

resource "aws_cloudfront_distribution" "cdn_webapp_distribution" {
  default_cache_behavior {
    allowed_methods          = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods           = ["GET", "HEAD"]
    target_origin_id         = "Origin-Webapp-Dev"
    cache_policy_id          = aws_cloudfront_cache_policy.cdn_managed_caching_disabled_cache_policy.id
    origin_request_policy_id = aws_cloudfront_origin_request_policy.cdn_managed_all_viewer_origin_request_policy.id
  }
}

No more unnecessary custom policies… and no more hardcoded IDs for managed policies!