CloudFront recently added a new feature that allows native header management for CloudFront distributions. Since Terraform support for it landed shortly thereafter, I took the opportunity to update this site's configuration and drop the custom CloudFront function that I was previously using.
It's a trivial example, since it's just setting a single header (following the lead of sites like GitHub), but here's the diff in case it's useful:
diff --git a/infra.tf/add_response_headers.js b/infra.tf/add_response_headers.js
deleted file mode 100644
index 9cfea6a..0000000
--- a/infra.tf/add_response_headers.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * CloudFront function package
- *
- * @packageDocumentation
- */
-
-/** Add headers to response */
-function handler(event) {
- // var request = event.request;
- var response = event.response;
- var headers = response.headers;
-
- // Disable FLoC
- headers['permissions-policy'] = { value: 'interest-cohort=()' };
-
- return response;
-}
diff --git a/infra.tf/main.tf b/infra.tf/main.tf
index fc4ffc8..aeb0c97 100644
--- a/infra.tf/main.tf
+++ b/infra.tf/main.tf
@@ -6,7 +6,7 @@ terraform {
required_providers {
aws = {
source = "hashicorp/aws"
- version = "~> 3.0"
+ version = "~> 3.64"
}
github = {
source = "integrations/github"
diff --git a/infra.tf/www.tf b/infra.tf/www.tf
index fc9c158..cb271c6 100644
--- a/infra.tf/www.tf
+++ b/infra.tf/www.tf
@@ -105,13 +105,19 @@ resource "aws_cloudfront_function" "rewrite_directory_index" {
name = "${terraform.workspace}-rewrite-directory-index"
runtime = "cloudfront-js-1.0"
}
-resource "aws_cloudfront_function" "add_response_headers" {
+
+resource "aws_cloudfront_response_headers_policy" "add_response_headers" {
provider = aws.virginia
- code = file("${path.module}/add_response_headers.js")
- comment = "Add header(s) to reponses"
- name = "${terraform.workspace}-add-response-headers"
- runtime = "cloudfront-js-1.0"
+ name = "${terraform.workspace}-add-response-headers"
+
+ custom_headers_config {
+ items {
+ header = "permissions-policy"
+ override = true
+ value = "interest-cohort=()"
+ }
+ }
}
resource "aws_cloudfront_distribution" "troyready_dot_com" {
@@ -132,6 +138,7 @@ resource "aws_cloudfront_distribution" "troyready_dot_com" {
default_ttl = 86400
max_ttl = 31536000
min_ttl = 0
+ response_headers_policy_id = aws_cloudfront_response_headers_policy.add_response_headers.id
target_origin_id = "s3-cloudfront"
viewer_protocol_policy = "redirect-to-https"
@@ -157,11 +164,6 @@ resource "aws_cloudfront_distribution" "troyready_dot_com" {
event_type = "viewer-request"
function_arn = aws_cloudfront_function.rewrite_directory_index.arn
}
-
- function_association {
- event_type = "viewer-response"
- function_arn = aws_cloudfront_function.add_response_headers.arn
- }
}
origin {