Capstone: A Static Website on AWS

Build a production-ready static site on AWS with Terraform: a private S3 bucket behind CloudFront with Origin Access Control, optional custom domain, tests, and two environments.

By The Dark DebuggerUpdated 30 min read

This capstone pulls the whole Terraform track together into one project you could hand to a team: a reusable module that hosts a static website from a private S3 bucket behind CloudFront, with HTTPS, security headers, an optional custom domain with an ACM certificate, file uploads with correct content types, staging and prod environments, and a test suite. It uses everything from modules, environments and testing. One thing up front: I built and verified it without an AWS account, so it has been formatted, validated, tested against a mocked AWS provider and planned with dummy credentials, but never applied. The footer has the details.

What we're building

A company marketing site, www.acme.example: plain HTML, CSS, JavaScript and images, no server. The naive version is an S3 bucket with "static website hosting" switched on and a public-read policy. It works, but the bucket is public, it serves plain HTTP only, and every request goes to one AWS region.

The version teams actually run looks like this:

browser ──HTTPS──> CloudFront edge ──signed (OAC)──> private S3 bucket
                     │  redirect HTTP to HTTPS          (Block Public Access on,
                     │  security headers                 ACLs disabled,
                     │  /about/ -> /about/index.html     versioned, encrypted)
                     │  403/404 -> /404.html
                     └─ optional: www.acme.example via Route 53 alias
                        + ACM certificate (issued in us-east-1)
  • S3 stores the files and stays completely private.
  • CloudFront serves them from edge locations over HTTPS, caches them, adds security headers, and is the only thing allowed to read the bucket.
  • Origin Access Control (OAC) makes CloudFront sign every request to S3, and the bucket policy accepts only requests signed on behalf of this one distribution.
  • ACM and Route 53 add the custom domain when you ask for one.

Project layout

.
├── envs
│   ├── prod
│   │   ├── backend.tfbackend
│   │   ├── main.tf
│   │   └── terraform.tfvars
│   └── staging
│       ├── backend.tfbackend
│       ├── main.tf
│       └── terraform.tfvars
├── modules
│   └── static-site
│       ├── cloudfront.tf
│       ├── dns.tf
│       ├── functions
│       │   └── rewrite-index.js
│       ├── objects.tf
│       ├── outputs.tf
│       ├── s3.tf
│       ├── tests
│       │   └── static_site.tftest.hcl
│       ├── variables.tf
│       └── versions.tf
└── site
    ├── 404.html
    ├── about
    │   └── index.html
    ├── css
    │   └── site.css
    ├── images
    │   └── logo.svg
    ├── index.html
    ├── js
    │   └── app.js
    └── robots.txt

The module is split into files by concern rather than one long main.tf, which makes code review easier: a change to caching touches cloudfront.tf, a change to uploads touches objects.tf.

The module, file by file

versions.tf: a module that needs two AWS providers

terraform {
  required_version = ">= 1.9"
 
  required_providers {
    aws = {
      source                = "hashicorp/aws"
      version               = ">= 6.0"
      configuration_aliases = [aws.us_east_1]
    }
  }
}

CloudFront only accepts certificates from ACM in us-east-1, wherever the rest of your infrastructure lives. configuration_aliases declares that this module expects a second, aliased AWS provider from its caller. The module never configures a provider itself; the root module decides which region and account each one uses. >= 1.9 is there because of the cross-variable validation below.

variables.tf: the interface

variable "name" {
  description = "Prefix for resource names, for example acme-prod-www."
  type        = string
 
  validation {
    condition     = can(regex("^[a-z0-9-]{3,40}$", var.name))
    error_message = "name must be 3-40 lowercase letters, digits or hyphens."
  }
}
 
variable "bucket_name" {
  description = "Globally unique S3 bucket name for the site files."
  type        = string
}
 
variable "site_dir" {
  description = "Local directory whose files are uploaded to the bucket."
  type        = string
}
 
variable "domain_name" {
  description = "Custom domain, such as www.example.com. Null serves the site on the CloudFront domain only."
  type        = string
  default     = null
 
  validation {
    condition     = var.domain_name == null || var.hosted_zone_id != null
    error_message = "hosted_zone_id is required when domain_name is set."
  }
}
 
variable "hosted_zone_id" {
  description = "Route 53 hosted zone that contains domain_name."
  type        = string
  default     = null
}
 
variable "price_class" {
  description = "CloudFront price class: which edge locations serve the site."
  type        = string
  default     = "PriceClass_100"
 
  validation {
    condition     = contains(["PriceClass_100", "PriceClass_200", "PriceClass_All"], var.price_class)
    error_message = "price_class must be PriceClass_100, PriceClass_200 or PriceClass_All."
  }
}
 
variable "html_max_age" {
  description = "Cache-Control max-age in seconds for HTML files."
  type        = number
  default     = 300
}
 
variable "asset_max_age" {
  description = "Cache-Control max-age in seconds for everything else."
  type        = number
  default     = 86400
}
 
variable "tags" {
  description = "Extra tags for resources that support them."
  type        = map(string)
  default     = {}
}

The domain_name validation refers to another variable, hosted_zone_id. Terraform has allowed that since 1.9, and it turns a confusing Route 53 error at apply time into a clear message at plan time.

s3.tf: a bucket nobody can read directly

resource "aws_s3_bucket" "site" {
  bucket = var.bucket_name
  tags   = var.tags
}
 
# ACLs off: the bucket owner owns every object.
resource "aws_s3_bucket_ownership_controls" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}
 
resource "aws_s3_bucket_public_access_block" "site" {
  bucket                  = aws_s3_bucket.site.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
 
resource "aws_s3_bucket_server_side_encryption_configuration" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}
 
# Versioning makes a bad upload reversible; old versions expire after 30 days.
resource "aws_s3_bucket_versioning" "site" {
  bucket = aws_s3_bucket.site.id
 
  versioning_configuration {
    status = "Enabled"
  }
}
 
resource "aws_s3_bucket_lifecycle_configuration" "site" {
  bucket = aws_s3_bucket.site.id
 
  rule {
    id     = "expire-old-versions"
    status = "Enabled"
 
    filter {}
 
    noncurrent_version_expiration {
      noncurrent_days = 30
    }
  }
}
 
# Only this CloudFront distribution may read objects.
resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
 
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Sid       = "AllowCloudFrontRead"
      Effect    = "Allow"
      Principal = { Service = "cloudfront.amazonaws.com" }
      Action    = "s3:GetObject"
      Resource  = "${aws_s3_bucket.site.arn}/*"
      Condition = {
        StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.site.arn }
      }
    }]
  })
 
  depends_on = [aws_s3_bucket_public_access_block.site]
}

The policy grants s3:GetObject to the CloudFront service, but the AWS:SourceArn condition narrows it to this one distribution. Without that condition, any CloudFront distribution in any AWS account could be pointed at your bucket. I build the policy with jsonencode() rather than an aws_iam_policy_document data source so the JSON is computed by Terraform itself, which keeps it testable with a mocked provider.

cloudfront.tf: the front door

locals {
  origin_id = "site-bucket"
  aliases   = var.domain_name == null ? [] : [var.domain_name]
 
  # AWS managed cache policy "CachingOptimized" (honors Cache-Control from S3).
  caching_optimized_policy_id = "658327ea-f89d-4fab-a63d-7e88639e58f6"
}
 
resource "aws_cloudfront_origin_access_control" "site" {
  name                              = var.name
  description                       = "Signed requests from CloudFront to ${var.bucket_name}"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}
 
resource "aws_cloudfront_function" "rewrite_index" {
  name    = "${var.name}-rewrite-index"
  runtime = "cloudfront-js-2.0"
  comment = "Serve /about/ and /about from /about/index.html"
  publish = true
  code    = file("${path.module}/functions/rewrite-index.js")
}
 
resource "aws_cloudfront_response_headers_policy" "security" {
  name = "${var.name}-security-headers"
 
  security_headers_config {
    strict_transport_security {
      access_control_max_age_sec = 63072000
      include_subdomains         = true
      preload                    = true
      override                   = true
    }
 
    content_type_options {
      override = true
    }
 
    frame_options {
      frame_option = "DENY"
      override     = true
    }
 
    referrer_policy {
      referrer_policy = "strict-origin-when-cross-origin"
      override        = true
    }
 
    content_security_policy {
      content_security_policy = "default-src 'self'; img-src 'self' data:; object-src 'none'; frame-ancestors 'none'"
      override                = true
    }
  }
}
 
resource "aws_cloudfront_distribution" "site" {
  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2and3"
  comment             = var.name
  default_root_object = "index.html"
  price_class         = var.price_class
  aliases             = local.aliases
 
  origin {
    origin_id                = local.origin_id
    domain_name              = aws_s3_bucket.site.bucket_regional_domain_name
    origin_access_control_id = aws_cloudfront_origin_access_control.site.id
  }
 
  default_cache_behavior {
    target_origin_id           = local.origin_id
    viewer_protocol_policy     = "redirect-to-https"
    allowed_methods            = ["GET", "HEAD"]
    cached_methods             = ["GET", "HEAD"]
    compress                   = true
    cache_policy_id            = local.caching_optimized_policy_id
    response_headers_policy_id = aws_cloudfront_response_headers_policy.security.id
 
    function_association {
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.rewrite_index.arn
    }
  }
 
  # The bucket is private, so S3 answers 403 (not 404) for a missing key.
  custom_error_response {
    error_code            = 403
    response_code         = 404
    response_page_path    = "/404.html"
    error_caching_min_ttl = 60
  }
 
  custom_error_response {
    error_code            = 404
    response_code         = 404
    response_page_path    = "/404.html"
    error_caching_min_ttl = 60
  }
 
  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }
 
  viewer_certificate {
    cloudfront_default_certificate = var.domain_name == null
    acm_certificate_arn            = var.domain_name == null ? null : aws_acm_certificate_validation.site[0].certificate_arn
    ssl_support_method             = var.domain_name == null ? null : "sni-only"
    minimum_protocol_version       = var.domain_name == null ? "TLSv1" : "TLSv1.2_2021"
  }
 
  tags = var.tags
}

The details that matter:

  • The origin is the bucket's REST endpoint (bucket_regional_domain_name), not the S3 website endpoint. Website endpoints don't support OAC and require a public bucket.
  • Two error responses. CloudFront's signed requests may only GetObject, not list the bucket, so S3 answers a missing key with 403 Access Denied rather than 404. Both are mapped to /404.html with a real 404 status, so visitors see your page and search engines see the correct code.
  • CachingOptimized is an AWS managed cache policy with a fixed, documented ID. Referencing the ID directly avoids a data source lookup at plan time. It respects the Cache-Control headers we set on each object.
  • viewer_certificate switches on domain_name. Without a domain, the distribution uses CloudFront's own certificate on its *.cloudfront.net name, and CloudFront requires TLSv1 as the minimum there. With a domain, it uses the ACM certificate and TLS 1.2 or newer.
  • The response headers policy adds HSTS, X-Content-Type-Options, X-Frame-Options, a referrer policy and a content security policy to every response. Adjust the CSP if your site loads scripts or fonts from other origins.

functions/rewrite-index.js: directory URLs

S3 has no concept of a directory index, so /about/ would be a 403 (and then our 404 page). A CloudFront Function on viewer requests rewrites the URI before the cache lookup:

// Viewer-request function: S3 has no directory index, so map
// "/about/" and "/about" to "/about/index.html". Paths with a file
// extension ("/css/site.css") pass through unchanged.
function handler(event) {
  var request = event.request;
  var uri = request.uri;
 
  if (uri.endsWith('/')) {
    request.uri = uri + 'index.html';
  } else if (!uri.split('/').pop().includes('.')) {
    request.uri = uri + '/index.html';
  }
 
  return request;
}

I can't run CloudFront without an account, but the handler is a plain function, so I tested its logic with Node.js and a ten-line harness (test-rewrite.js) that loads the file and calls handler with sample URIs:

// test-rewrite.js: exercise the CloudFront function's handler locally.
const fs = require("fs");
const src = fs.readFileSync(process.argv[2], "utf8");
const handler = new Function(src + "\nreturn handler;")();
 
for (const uri of ["/", "/about/", "/about", "/css/site.css", "/blog/2026/launch", "/robots.txt"]) {
  const out = handler({ request: { uri } });
  console.log(uri.padEnd(20), "->", out.uri);
}
node test-rewrite.js modules/static-site/functions/rewrite-index.js
/                    -> /index.html
/about/              -> /about/index.html
/about               -> /about/index.html
/css/site.css        -> /css/site.css
/blog/2026/launch    -> /blog/2026/launch/index.html
/robots.txt          -> /robots.txt

dns.tf: the optional custom domain

# Everything in this file exists only when a custom domain is set.
 
# CloudFront only accepts certificates issued in us-east-1.
resource "aws_acm_certificate" "site" {
  count    = var.domain_name == null ? 0 : 1
  provider = aws.us_east_1
 
  domain_name       = var.domain_name
  validation_method = "DNS"
  tags              = var.tags
 
  lifecycle {
    create_before_destroy = true
  }
}
 
# Keyed by the domain name, which is known at plan time. Keying by
# domain_validation_options fails whenever those values are not known yet.
resource "aws_route53_record" "cert_validation" {
  for_each = var.domain_name == null ? toset([]) : toset([var.domain_name])
 
  zone_id         = var.hosted_zone_id
  name            = one([for o in aws_acm_certificate.site[0].domain_validation_options : o.resource_record_name if o.domain_name == each.key])
  type            = one([for o in aws_acm_certificate.site[0].domain_validation_options : o.resource_record_type if o.domain_name == each.key])
  records         = [one([for o in aws_acm_certificate.site[0].domain_validation_options : o.resource_record_value if o.domain_name == each.key])]
  ttl             = 300
  allow_overwrite = true
}
 
resource "aws_acm_certificate_validation" "site" {
  count    = var.domain_name == null ? 0 : 1
  provider = aws.us_east_1
 
  certificate_arn         = aws_acm_certificate.site[0].arn
  validation_record_fqdns = [for r in aws_route53_record.cert_validation : r.fqdn]
}
 
resource "aws_route53_record" "alias" {
  for_each = var.domain_name == null ? toset([]) : toset(["A", "AAAA"])
 
  zone_id = var.hosted_zone_id
  name    = var.domain_name
  type    = each.key
 
  alias {
    name                   = aws_cloudfront_distribution.site.domain_name
    zone_id                = aws_cloudfront_distribution.site.hosted_zone_id
    evaluate_target_health = false
  }
}

The flow on apply: request a certificate in us-east-1, publish the DNS record ACM asks for, wait in aws_acm_certificate_validation until ACM confirms, then attach the certificate to the distribution (the viewer_certificate block reads the validated ARN, which creates that ordering) and point A and AAAA alias records at CloudFront.

You'll often see the validation records written with for_each = { for dvo in aws_acm_certificate.site[0].domain_validation_options : ... }. That works against the real AWS provider, which fills in the domain names at plan time, but for_each keys must be known during planning, and under a mocked provider (or after some refactors) they aren't. Keying on var.domain_name is known in every situation, so I use that.

objects.tf: uploading the site

locals {
  content_types = {
    html  = "text/html; charset=utf-8"
    css   = "text/css; charset=utf-8"
    js    = "text/javascript; charset=utf-8"
    json  = "application/json"
    txt   = "text/plain; charset=utf-8"
    xml   = "application/xml"
    svg   = "image/svg+xml"
    png   = "image/png"
    jpg   = "image/jpeg"
    webp  = "image/webp"
    ico   = "image/x-icon"
    woff2 = "font/woff2"
  }
 
  site_files = fileset(var.site_dir, "**")
}
 
resource "aws_s3_object" "site" {
  for_each = local.site_files
 
  bucket = aws_s3_bucket.site.id
  key    = each.value
  source = "${var.site_dir}/${each.value}"
 
  # source_hash (not etag) so edits are detected even with SSE-KMS.
  source_hash = filemd5("${var.site_dir}/${each.value}")
 
  content_type = lookup(
    local.content_types,
    lower(try(regex("\\.([^.]+)$", each.value)[0], "")),
    "application/octet-stream",
  )
 
  cache_control = endswith(each.value, ".html") ? "public, max-age=${var.html_max_age}" : "public, max-age=${var.asset_max_age}"
}
  • fileset(var.site_dir, "**") returns every file path relative to the site directory, which becomes both the for_each key and the S3 key.
  • Content types matter. S3 doesn't guess them from the extension when Terraform uploads a file. Without content_type, every file is served as application/octet-stream and browsers download your HTML instead of rendering it. The regex pulls out the extension; try() handles files with none, and unknown extensions fall back to application/octet-stream.
  • source_hash tells Terraform when a file changed. The commonly copied etag = filemd5(...) only works while the bucket uses SSE-S3 encryption; with SSE-KMS the ETag is no longer an MD5 and you get a perpetual diff.
  • HTML gets a short cache lifetime (five minutes), everything else a day. The next sections come back to why.

For a site with thousands of files, one Terraform resource per file gets slow. At that size, keep the bucket and distribution in Terraform and upload with aws s3 sync in the deployment pipeline instead.

outputs.tf

output "bucket_name" {
  description = "Name of the private bucket holding the site files."
  value       = aws_s3_bucket.site.id
}
 
output "distribution_id" {
  description = "CloudFront distribution ID, needed for cache invalidations."
  value       = aws_cloudfront_distribution.site.id
}
 
output "site_url" {
  description = "Public URL of the site."
  value       = "https://${coalesce(var.domain_name, aws_cloudfront_distribution.site.domain_name)}/"
}
 
output "uploaded_files" {
  description = "Number of files managed in the bucket."
  value       = length(aws_s3_object.site)
}

The environments

envs/staging/main.tf and envs/prod/main.tf are identical, following the directory-per-environment layout from the environments tutorial:

terraform {
  required_version = ">= 1.9"
 
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
 
  backend "s3" {}
}
 
variable "environment" {
  type = string
}
 
variable "domain_name" {
  type    = string
  default = null
}
 
variable "hosted_zone_id" {
  type    = string
  default = null
}
 
locals {
  name = "acme-${var.environment}-www"
 
  tags = {
    Project     = "acme-www"
    Environment = var.environment
    ManagedBy   = "terraform"
    CostCenter  = "cc-2001"
  }
}
 
provider "aws" {
  region = "eu-west-1"
 
  default_tags {
    tags = local.tags
  }
}
 
# CloudFront certificates must live in us-east-1.
provider "aws" {
  alias  = "us_east_1"
  region = "us-east-1"
 
  default_tags {
    tags = local.tags
  }
}
 
module "site" {
  source = "../../modules/static-site"
 
  providers = {
    aws           = aws
    aws.us_east_1 = aws.us_east_1
  }
 
  name           = local.name
  bucket_name    = "${local.name}-site"
  site_dir       = "${path.root}/../../site"
  domain_name    = var.domain_name
  hosted_zone_id = var.hosted_zone_id
}
 
output "site_url" {
  value = module.site.site_url
}
 
output "distribution_id" {
  value = module.site.distribution_id
}
 
output "bucket_name" {
  value = module.site.bucket_name
}

The providers map hands the module its two AWS providers. Bucket names are global across all AWS accounts, so in real life you'll probably need something more unique than acme-prod-www-site, such as a suffix with the account ID.

envs/staging/terraform.tfvars serves staging on its CloudFront domain:

environment = "staging"

envs/prod/terraform.tfvars adds the custom domain:

environment    = "prod"
domain_name    = "www.acme.example"
hosted_zone_id = "Z0123456789ABCDEFGHIJ"

And envs/prod/backend.tfbackend (staging's names its own bucket):

bucket       = "acme-terraform-state-prod"
key          = "www/terraform.tfstate"
region       = "eu-west-1"
use_lockfile = true

Testing the module with a mocked AWS provider

modules/static-site/tests/static_site.tftest.hcl checks the properties that matter for security and correctness. Two mocked providers stand in for the default and us_east_1 AWS providers:

mock_provider "aws" {
  # The provider validates function_arn on the distribution, so the
  # mocked function needs an ARN-shaped value instead of a random string.
  mock_resource "aws_cloudfront_function" {
    defaults = {
      arn = "arn:aws:cloudfront::111122223333:function/acme-test-www-rewrite-index"
    }
  }
}
 
mock_provider "aws" {
  alias = "us_east_1"
}
 
variables {
  name        = "acme-test-www"
  bucket_name = "acme-test-www-site"
  site_dir    = "../../site"
}
 
run "bucket_is_private" {
  command = plan
 
  assert {
    condition = alltrue([
      aws_s3_bucket_public_access_block.site.block_public_acls,
      aws_s3_bucket_public_access_block.site.block_public_policy,
      aws_s3_bucket_public_access_block.site.ignore_public_acls,
      aws_s3_bucket_public_access_block.site.restrict_public_buckets,
    ])
    error_message = "The site bucket must block all public access."
  }
 
  assert {
    condition     = aws_s3_bucket_ownership_controls.site.rule[0].object_ownership == "BucketOwnerEnforced"
    error_message = "ACLs must be disabled (BucketOwnerEnforced)."
  }
}
 
run "uploads_every_file_with_its_content_type" {
  command = plan
 
  assert {
    condition     = length(aws_s3_object.site) == length(fileset("../../site", "**"))
    error_message = "Every file in site_dir should become an S3 object."
  }
 
  assert {
    condition     = aws_s3_object.site["index.html"].content_type == "text/html; charset=utf-8"
    error_message = "HTML must be served as text/html."
  }
 
  assert {
    condition     = aws_s3_object.site["css/site.css"].content_type == "text/css; charset=utf-8"
    error_message = "CSS must be served as text/css."
  }
 
  assert {
    condition     = aws_s3_object.site["images/logo.svg"].content_type == "image/svg+xml"
    error_message = "SVG must be served as image/svg+xml."
  }
 
  assert {
    condition     = aws_s3_object.site["about/index.html"].cache_control == "public, max-age=300"
    error_message = "HTML should be cached briefly."
  }
}
 
run "cloudfront_uses_https_and_oac" {
  command = plan
 
  assert {
    condition     = aws_cloudfront_distribution.site.default_cache_behavior[0].viewer_protocol_policy == "redirect-to-https"
    error_message = "Plain HTTP must redirect to HTTPS."
  }
 
  assert {
    condition     = aws_cloudfront_origin_access_control.site.signing_behavior == "always"
    error_message = "CloudFront must sign every request to S3."
  }
 
  assert {
    condition     = length(aws_acm_certificate.site) == 0 && aws_cloudfront_distribution.site.viewer_certificate[0].cloudfront_default_certificate
    error_message = "Without a domain, the default CloudFront certificate is used."
  }
}
 
run "bucket_policy_trusts_only_this_distribution" {
  override_resource {
    target = aws_cloudfront_distribution.site
    values = {
      arn = "arn:aws:cloudfront::111122223333:distribution/E2EXAMPLE123"
    }
  }
 
  override_resource {
    target = aws_s3_bucket.site
    values = {
      arn = "arn:aws:s3:::acme-test-www-site"
    }
  }
 
  assert {
    condition     = jsondecode(aws_s3_bucket_policy.site.policy).Statement[0].Condition.StringEquals["AWS:SourceArn"] == "arn:aws:cloudfront::111122223333:distribution/E2EXAMPLE123"
    error_message = "The bucket policy must be scoped to this distribution."
  }
 
  assert {
    condition     = jsondecode(aws_s3_bucket_policy.site.policy).Statement[0].Resource == "arn:aws:s3:::acme-test-www-site/*"
    error_message = "The policy should grant read on objects only."
  }
}
 
run "custom_domain_adds_certificate_and_dns" {
  command = plan
 
  variables {
    domain_name    = "www.acme.example"
    hosted_zone_id = "Z0123456789ABCDEFGHIJ"
  }
 
  assert {
    condition     = length(aws_acm_certificate.site) == 1 && length(aws_route53_record.alias) == 2
    error_message = "A custom domain needs a certificate and A/AAAA alias records."
  }
 
  assert {
    condition     = aws_cloudfront_distribution.site.viewer_certificate[0].minimum_protocol_version == "TLSv1.2_2021"
    error_message = "Custom domains must require TLS 1.2 or newer."
  }
 
  assert {
    condition     = contains(aws_cloudfront_distribution.site.aliases, "www.acme.example")
    error_message = "The distribution must answer for the custom domain."
  }
}
 
run "domain_without_zone_is_rejected" {
  command = plan
 
  variables {
    domain_name = "www.acme.example"
  }
 
  expect_failures = [var.domain_name]
}

The 111122223333 account ID in the fake ARNs is the placeholder AWS uses in its own documentation.

cd modules/static-site
terraform init -backend=false
terraform test
tests/static_site.tftest.hcl... in progress
  run "bucket_is_private"... pass
  run "uploads_every_file_with_its_content_type"... pass
  run "cloudfront_uses_https_and_oac"... pass
  run "bucket_policy_trusts_only_this_distribution"... pass
  run "custom_domain_adds_certificate_and_dns"... pass
  run "domain_without_zone_is_rejected"... pass
tests/static_site.tftest.hcl... tearing down
tests/static_site.tftest.hcl... pass
 
Success! 6 passed, 0 failed.

Planning both environments offline

A real plan needs AWS credentials and the state bucket. To check the environments without them, I copied an override file into each environment directory. It swaps the S3 backend for a local one and tells both providers not to call AWS during setup:

# offline_override.tf: copied into an environment directory to run
# `terraform plan` without an AWS account. Never commit it.
terraform {
  backend "local" {}
}
 
provider "aws" {
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
 
provider "aws" {
  alias                       = "us_east_1"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}

With dummy access keys in the environment, staging initializes, validates and plans:

cd envs/staging
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
terraform init
terraform validate
terraform plan -out=tfplan > plan.txt
grep -E '^  # |^Plan:' plan.txt
[…]
Success! The configuration is valid.
 
  # module.site.aws_cloudfront_distribution.site will be created
  # module.site.aws_cloudfront_function.rewrite_index will be created
  # module.site.aws_cloudfront_origin_access_control.site will be created
  # module.site.aws_cloudfront_response_headers_policy.security will be created
  # module.site.aws_s3_bucket.site will be created
  # module.site.aws_s3_bucket_lifecycle_configuration.site will be created
  # module.site.aws_s3_bucket_ownership_controls.site will be created
  # module.site.aws_s3_bucket_policy.site will be created
  # module.site.aws_s3_bucket_public_access_block.site will be created
  # module.site.aws_s3_bucket_server_side_encryption_configuration.site will be created
  # module.site.aws_s3_bucket_versioning.site will be created
  # module.site.aws_s3_object.site["404.html"] will be created
  # module.site.aws_s3_object.site["about/index.html"] will be created
  # module.site.aws_s3_object.site["css/site.css"] will be created
  # module.site.aws_s3_object.site["images/logo.svg"] will be created
  # module.site.aws_s3_object.site["index.html"] will be created
  # module.site.aws_s3_object.site["js/app.js"] will be created
  # module.site.aws_s3_object.site["robots.txt"] will be created
Plan: 18 to add, 0 to change, 0 to destroy.

Eighteen resources, none of them DNS: staging has no domain. One uploaded file in detail, with the default tags from the provider in tags_all:

  # module.site.aws_s3_object.site["about/index.html"] will be created
  + resource "aws_s3_object" "site" {
      […]
      + bucket                 = (known after apply)
      + cache_control          = "public, max-age=300"
      […]
      + content_type           = "text/html; charset=utf-8"
      + etag                   = (known after apply)
      + force_destroy          = false
      + id                     = (known after apply)
      + key                    = "about/index.html"
      […]
      + source                 = "./../../site/about/index.html"
      + source_hash            = "adfd287c26b2534e631cf68ebf906ee6"
      + storage_class          = (known after apply)
      + tags_all               = {
          + "CostCenter"  = "cc-2001"
          + "Environment" = "staging"
          + "ManagedBy"   = "terraform"
          + "Project"     = "acme-www"
        }
      + version_id             = (known after apply)
    }

The plan JSON gives a quick review of every upload's headers:

terraform show -json tfplan | jq -r '.resource_changes[] | select(.type=="aws_s3_object") | "\(.change.after.key)\t\(.change.after.content_type)\t\(.change.after.cache_control)"'
404.html	text/html; charset=utf-8	public, max-age=300
about/index.html	text/html; charset=utf-8	public, max-age=300
css/site.css	text/css; charset=utf-8	public, max-age=86400
images/logo.svg	image/svg+xml	public, max-age=86400
index.html	text/html; charset=utf-8	public, max-age=300
js/app.js	text/javascript; charset=utf-8	public, max-age=86400
robots.txt	text/plain; charset=utf-8	public, max-age=86400

Prod, with its custom domain, adds the certificate, its validation and three DNS records:

  # module.site.aws_acm_certificate.site[0] will be created
  # module.site.aws_acm_certificate_validation.site[0] will be created
  # module.site.aws_cloudfront_distribution.site will be created
  […]
  # module.site.aws_route53_record.alias["A"] will be created
  # module.site.aws_route53_record.alias["AAAA"] will be created
  # module.site.aws_route53_record.cert_validation["www.acme.example"] will be created
  […]
Plan: 23 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + bucket_name     = (known after apply)
  + distribution_id = (known after apply)
  + site_url        = "https://www.acme.example/"

Deploying for real

This is the sequence for a real account. I did not run it; everything above stops at the plan. Delete offline_override.tf first.

cd envs/staging
terraform init -backend-config=backend.tfbackend
terraform plan -out=tfplan
terraform apply tfplan
terraform output site_url

Expect the first apply to take a while: a new CloudFront distribution typically takes several minutes to deploy to all edge locations, and in prod the certificate validation waits for DNS to propagate. In a team, this runs through the pipeline from Testing and CI: plan on pull request, apply the saved plan after approval, staging first and prod after.

Updating content and invalidating the cache

Edit a file in site/ and the next plan shows an in-place update of that one aws_s3_object (its source_hash changed). The new file is in S3 right after the apply, but CloudFront keeps serving its cached copy until it expires. That's what the two cache lifetimes are for:

  • HTML: 5 minutes. Content updates show up within minutes without doing anything.
  • CSS, JavaScript, images: 1 day. Fine for files that rarely change. For assets that do change, use fingerprinted file names (app.3f9c2b.js, produced by your build tool) and raise asset_max_age to a year: a new version is a new URL, so it never needs invalidating.

When you need a change live immediately, invalidate the paths. I didn't run this (it needs an account and the AWS CLI):

aws cloudfront create-invalidation \
  --distribution-id "$(terraform output -raw distribution_id)" \
  --paths "/index.html" "/404.html" "/about/*"

Invalidations are billed per path beyond a monthly free allowance, and a wildcard like /about/* counts as one path. Invalidate the HTML you changed, not /* on every deploy out of habit.

Cost notes

For a small marketing site, the bill is small but not zero, and it's worth knowing where it comes from. Check the AWS pricing pages for current numbers; I'm deliberately not quoting prices that change.

  • CloudFront charges for data transfer out and for requests, with a monthly free allowance on pay-as-you-go pricing that covers many small sites entirely. PriceClass_100 serves from edge locations in North America and Europe only, the cheapest group; visitors elsewhere are served from the nearest of those, a bit more slowly. Use PriceClass_All if your audience is global.
  • CloudFront Functions are billed per invocation, again with a free allowance. The rewrite function runs on every viewer request, so a busy site pays for it.
  • S3 storage for a site is negligible, but versioning keeps every old copy of every file, which is why the lifecycle rule expires noncurrent versions after 30 days. Requests from CloudFront to S3 only happen on cache misses, so longer cache lifetimes cut those too.
  • Route 53 charges a monthly fee per hosted zone and a small amount per query; alias queries to CloudFront are not charged.
  • ACM public certificates used with CloudFront cost nothing and renew themselves as long as the validation record stays in DNS. Don't delete it.

Security notes

  • No public bucket, ever. Block Public Access is on, ACLs are disabled, and the only principal allowed to read is CloudFront, scoped by AWS:SourceArn to this distribution. If someone finds the bucket name, they get Access Denied.
  • OAC, not the legacy origin access identity (OAI). OAC signs requests with SigV4, works with SSE-KMS encrypted objects, and is what AWS recommends for new distributions.
  • HTTPS only: HTTP redirects to HTTPS, custom domains require TLS 1.2 or newer, and HSTS tells browsers to never try plain HTTP again. HSTS with preload is hard to undo, so only keep it if every subdomain can do HTTPS.
  • Security headers come from the response headers policy, so they apply to every file, including the 404 page, without touching the HTML.
  • Least privilege for deployment. If a pipeline uploads content separately from Terraform, its role needs s3:PutObject and s3:DeleteObject on this bucket and cloudfront:CreateInvalidation on this distribution, nothing more. The Terraform role that creates the infrastructure is a different, more tightly guarded role.
  • State holds no secrets in this project, but it still lives in an encrypted, versioned backend, as in Terraform State.
  • Not included: AWS WAF in front of CloudFront (worth adding for sites that get attacked, at extra cost) and access logging. Both are natural next additions to the module.

Where you'll use this

This exact shape (private S3, CloudFront with OAC, ACM, Route 53) is how AWS teams host documentation sites, marketing sites, single-page applications (React, Vue, Angular builds are just static files), status pages and download portals. The module boundary is what makes it reusable: a new site is a new environment directory with a site_dir and a domain, and every site gets the same security settings and tests for free. For a single-page application, change the 403/404 custom_error_response entries to return /index.html with status 200, so the client-side router handles unknown paths.

Common mistakes

Validating a module that expects aliased providers on its own

My first terraform validate ran inside modules/static-site:

terraform validate
Error: Provider configuration not present
 
To work with aws_acm_certificate.site its original provider configuration at
provider["registry.terraform.io/hashicorp/aws"].us_east_1 is required, but it
has been removed. This occurs when a provider configuration is removed while
objects created by that provider still exist in the state. Re-add the
provider configuration to destroy aws_acm_certificate.site, after which you
can remove the provider configuration again.

The message talks about state, which is misleading here. The real cause: a module that declares configuration_aliases can't be validated as a root module, because nothing supplies the aws.us_east_1 configuration. Validate it through a caller (terraform validate in envs/staging printed Success! The configuration is valid.), and test it with terraform test, whose mock providers fill the alias.

Mocked values that the provider rejects

My first test run, before the mock_resource block was added:

  run "bucket_policy_trusts_only_this_distribution"... fail
 
Error: "default_cache_behavior.0.function_association.0.function_arn" (dnbh545o) is an invalid ARN: arn: invalid prefix
 
  with aws_cloudfront_distribution.site,
  on cloudfront.tf line 81, in resource "aws_cloudfront_distribution" "site":
  81:     function_association {

The plan-mode runs passed because the function's ARN is unknown during a plan. This run applies, so the mock invented a random string for the ARN, and the AWS provider's own validation of function_arn rejected it. The fix is a mock_resource default with an ARN-shaped value, applied to every run in the file.

Serving everything as application/octet-stream

Leave out content_type on aws_s3_object and S3 stores every file with the generic binary type. Browsers then download index.html instead of rendering it. Exercise 1 below shows the failing test that catches a missing mapping.

Pointing CloudFront at the S3 website endpoint

If you copy an older tutorial and use the bucket's website_endpoint as the origin, OAC can't sign the requests and you're pushed into making the bucket public. Use bucket_regional_domain_name and the CloudFront Function for directory indexes, as above.

Summary

  • The production pattern for static sites on AWS is a private S3 bucket behind CloudFront with Origin Access Control, and a bucket policy scoped by AWS:SourceArn to the one distribution.
  • A missing object in a private bucket returns 403, so map both 403 and 404 to your error page. A CloudFront Function handles directory URLs like /about/.
  • CloudFront certificates come from ACM in us-east-1. A module needing that second region declares configuration_aliases and receives both providers via providers = { ... }.
  • Upload with aws_s3_object over fileset(), setting content_type from the extension, cache_control per file type, and source_hash for change detection.
  • Short cache lifetimes for HTML and fingerprinted, long-lived assets make invalidations rare. When needed, invalidate specific paths.
  • for_each keys must be known at plan time; key on input variables rather than provider-computed attributes.
  • Mock-provider tests verify the module's security properties offline; a plan with dummy credentials and an override file verifies the environments. A real apply is the remaining step.

Exercises

Exercise 1: Serve PDFs correctlyeasy

Marketing wants to publish files/catalog.pdf. Add the file, add a test run asserting it's served as application/pdf, watch the test fail, then fix the module.

Show Solution

Add the test run to tests/static_site.tftest.hcl:

run "pdf_is_served_as_pdf" {
  command = plan
 
  assert {
    condition     = aws_s3_object.site["files/catalog.pdf"].content_type == "application/pdf"
    error_message = "PDFs must be served as application/pdf, got ${aws_s3_object.site["files/catalog.pdf"].content_type}."
  }
}

With the file present but no mapping, the test fails:

  run "pdf_is_served_as_pdf"... fail
 
Error: Test assertion failed
 
  on tests/static_site.tftest.hcl line 152, in run "pdf_is_served_as_pdf":
 152:     condition     = aws_s3_object.site["files/catalog.pdf"].content_type == "application/pdf"
    ├────────────────
    │ Diff:
    │ --- actual
    │ +++ expected
    │ - "application/octet-stream"
    │ + "application/pdf"
 
 
PDFs must be served as application/pdf, got application/octet-stream.
[…]
Failure! 6 passed, 1 failed.

Add one line to local.content_types in objects.tf:

    pdf   = "application/pdf"
terraform test | tail -1
Success! 7 passed, 0 failed.

The fallback to application/octet-stream is a deliberate safe default, and a test per file type you care about catches the gap before visitors do.

Exercise 2: No HTML caching outside prodmedium

Content editors reviewing staging don't want to wait five minutes to see changes. Without changing the module, make staging serve HTML with max-age=0 while prod keeps 300 seconds. Verify it from the staging plan JSON.

Show Solution

The module already exposes html_max_age, so set it from the environment root in envs/staging/main.tf, and copy the same change into prod's identical file:

module "site" {
  source = "../../modules/static-site"
 
  providers = {
    aws           = aws
    aws.us_east_1 = aws.us_east_1
  }
 
  name           = local.name
  bucket_name    = "${local.name}-site"
  site_dir       = "${path.root}/../../site"
  domain_name    = var.domain_name
  hosted_zone_id = var.hosted_zone_id
  html_max_age   = var.environment == "prod" ? 300 : 0
}
terraform plan -out=tfplan > /dev/null
terraform show -json tfplan | jq -r '.resource_changes[] | select(.type == "aws_s3_object" and (.change.after.key | endswith(".html"))) | "\(.change.after.key)\t\(.change.after.cache_control)"'
404.html	public, max-age=0
about/index.html	public, max-age=0
index.html	public, max-age=0

Keeping the main.tf files identical and deciding by var.environment means prod can't drift from staging by accident; the only differences are the ones written as conditions.

Exercise 3: Output the invalidation commandmedium

Add a module output invalidate_html_command containing a ready-to-run aws cloudfront create-invalidation command for / and every HTML file, sorted. Test it with an apply-mode run.

Hint

Filter local.site_files with a for expression and endswith(), then join() the paths.

Show Solution

In outputs.tf:

output "invalidate_html_command" {
  description = "AWS CLI command that invalidates every HTML page after an upload."
  value = format(
    "aws cloudfront create-invalidation --distribution-id %s --paths %s",
    aws_cloudfront_distribution.site.id,
    join(" ", concat(["/"], [for f in sort(local.site_files) : "/${f}" if endswith(f, ".html")])),
  )
}

The test run:

run "invalidation_command_lists_html_pages" {
  assert {
    condition     = endswith(output.invalidate_html_command, "--paths / /404.html /about/index.html /index.html")
    error_message = "Unexpected command: ${output.invalidate_html_command}"
  }
}
terraform test -verbose 2>&1 | grep -E '^invalidate_html_command'
invalidate_html_command = "aws cloudfront create-invalidation --distribution-id 0a63h420 --paths / /404.html /about/index.html /index.html"
[…]

My first version of this test pinned the distribution ID with an override_resource setting id = "E2EXAMPLE123", and it failed: the mock kept inventing its own ID (g1lyk08f in that run) despite the override. Checking only the paths, which the module controls, made the test both correct and independent of the mock.

Exercise 4: Deny plain-HTTP access to the buckethard

CloudFront already talks to S3 over HTTPS, but a security review asks for the bucket policy to deny any request without TLS, from anyone. Add the statement and a test proving it's there, without breaking the existing policy test.

Show Solution

Replace the policy in s3.tf with a two-statement version. The Allow statement stays first, so the existing test's Statement[0] still points at it:

# Only this CloudFront distribution may read objects, and only over TLS.
resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
 
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid       = "AllowCloudFrontRead"
        Effect    = "Allow"
        Principal = { Service = "cloudfront.amazonaws.com" }
        Action    = "s3:GetObject"
        Resource  = "${aws_s3_bucket.site.arn}/*"
        Condition = {
          StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.site.arn }
        }
      },
      {
        Sid       = "DenyInsecureTransport"
        Effect    = "Deny"
        Principal = "*"
        Action    = "s3:*"
        Resource  = [aws_s3_bucket.site.arn, "${aws_s3_bucket.site.arn}/*"]
        Condition = {
          Bool = { "aws:SecureTransport" = "false" }
        }
      },
    ]
  })
 
  depends_on = [aws_s3_bucket_public_access_block.site]
}

The test looks for the Deny statement wherever it sits in the list:

run "bucket_policy_denies_plain_http" {
  override_resource {
    target = aws_s3_bucket.site
    values = {
      arn = "arn:aws:s3:::acme-test-www-site"
    }
  }
 
  assert {
    condition = anytrue([
      for s in jsondecode(aws_s3_bucket_policy.site.policy).Statement :
      s.Effect == "Deny" && try(s.Condition.Bool["aws:SecureTransport"], "") == "false"
    ])
    error_message = "The bucket policy must deny requests that don't use TLS."
  }
}

With exercises 1 and 3 also in place, the full suite:

tests/static_site.tftest.hcl... in progress
  run "bucket_is_private"... pass
  run "uploads_every_file_with_its_content_type"... pass
  run "cloudfront_uses_https_and_oac"... pass
  run "bucket_policy_trusts_only_this_distribution"... pass
  run "custom_domain_adds_certificate_and_dns"... pass
  run "domain_without_zone_is_rejected"... pass
  run "pdf_is_served_as_pdf"... pass
  run "invalidation_command_lists_html_pages"... pass
  run "bucket_policy_denies_plain_http"... pass
tests/static_site.tftest.hcl... tearing down
tests/static_site.tftest.hcl... pass
 
Success! 9 passed, 0 failed.

The try() in the condition matters: the Allow statement has no Bool condition, and without try() evaluating it would be an error rather than false. Searching with anytrue instead of indexing keeps the test valid if someone reorders the statements.


Tested with: Terraform v1.17.1 and hashicorp/aws v6.72.0 on Ubuntu 24.04 (WSL2, linux_amd64), Node.js v22.3.0, November 2026. Nothing in this article was applied to a real AWS account. What did run: terraform fmt -check, terraform validate (through the staging root module), the terraform test suite against mocked AWS providers (all runs shown, including the failures), and terraform plan for staging and prod with dummy credentials and the offline_override.tf file shown. The CloudFront Function's logic was exercised with Node.js on the Windows host rather than in CloudFront. The deployment and aws cloudfront create-invalidation commands were not run.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.