Chuyển đến nội dung

Bài 34 · Projects and Practice

Project: Host a Static Website with S3, CloudFront and Terraform

Build a complete static website stack with Terraform: private S3 bucket, CloudFront with origin access control, HTTPS certificate, DNS and a content-type upload map.

In this project you put the whole tutorial to work on a small, realistic task: hosting a static website (HTML, CSS, JavaScript) globally with HTTPS. The architecture is a standard one: files live in a private S3 bucket, and CloudFront (a CDN) serves them to the world. The bucket is never public; only CloudFront may read it.

The HCL below is complete but read-only here because it needs an AWS account. The runnable programs handle the parts that can be simulated: working out which files to upload with which content types, and validating the design.

CloudFront certificates must be created in us-east-1, wherever the rest of your stack lives. This is the most common surprise in this project, and it is why the configuration uses two AWS provider blocks.

Architecture

flowchart LR
  U["Visitor"] --> DNS["DNS: www.example.com (alias)"]
  DNS --> CF["CloudFront distribution"]
  ACM["ACM certificate (us-east-1)"] --> CF
  CF -->|"Origin Access Control (signed requests)"| S3[("Private S3 bucket")]

The bucket only accepts requests signed by this CloudFront distribution.

Step 1: providers and variables

HCL
terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.60" }
  }
}

provider "aws" {
  region = "eu-central-1"
}

provider "aws" {
  alias  = "us_east_1"
  region = "us-east-1"
}

variable "domain_name" {
  type = string
}

variable "site_dir" {
  type    = string
  default = "site"
}

variable "zone_id" {
  type        = string
  description = "Route 53 hosted zone ID for the domain."
}

Step 2: the private bucket

HCL
resource "aws_s3_bucket" "site" {
  bucket = "${replace(var.domain_name, ".", "-")}-site"
}

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
}

Step 3: certificate with DNS validation

HCL
resource "aws_acm_certificate" "site" {
  provider          = aws.us_east_1
  domain_name       = var.domain_name
  validation_method = "DNS"

  lifecycle { create_before_destroy = true }
}

resource "aws_route53_record" "validation" {
  for_each = {
    for o in aws_acm_certificate.site.domain_validation_options : o.domain_name => o
  }
  zone_id = var.zone_id
  name    = each.value.resource_record_name
  type    = each.value.resource_record_type
  records = [each.value.resource_record_value]
  ttl     = 60
}

resource "aws_acm_certificate_validation" "site" {
  provider                = aws.us_east_1
  certificate_arn         = aws_acm_certificate.site.arn
  validation_record_fqdns = [for r in aws_route53_record.validation : r.fqdn]
}

Terraform waits for the validation resource, so the distribution below is created only after the certificate is issued.

Step 4: CloudFront with origin access control

HCL
resource "aws_cloudfront_origin_access_control" "site" {
  name                              = "site-oac"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}

resource "aws_cloudfront_distribution" "site" {
  enabled             = true
  default_root_object = "index.html"
  aliases             = [var.domain_name]

  origin {
    domain_name              = aws_s3_bucket.site.bucket_regional_domain_name
    origin_id                = "s3-site"
    origin_access_control_id = aws_cloudfront_origin_access_control.site.id
  }

  default_cache_behavior {
    target_origin_id       = "s3-site"
    viewer_protocol_policy = "redirect-to-https"
    allowed_methods        = ["GET", "HEAD"]
    cached_methods         = ["GET", "HEAD"]
    cache_policy_id        = "658327ea-f89d-4fab-a63d-7e88639e58f6" # AWS managed CachingOptimized
  }

  custom_error_response {
    error_code         = 404
    response_code      = 404
    response_page_path = "/404.html"
  }

  restrictions {
    geo_restriction { restriction_type = "none" }
  }

  viewer_certificate {
    acm_certificate_arn = aws_acm_certificate_validation.site.certificate_arn
    ssl_support_method  = "sni-only"
    minimum_protocol_version = "TLSv1.2_2021"
  }
}

data "aws_iam_policy_document" "site" {
  statement {
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.site.arn}/*"]
    principals {
      type        = "Service"
      identifiers = ["cloudfront.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "AWS:SourceArn"
      values   = [aws_cloudfront_distribution.site.arn]
    }
  }
}

resource "aws_s3_bucket_policy" "site" {
  bucket = aws_s3_bucket.site.id
  policy = data.aws_iam_policy_document.site.json
}

Step 5: DNS alias to the distribution

HCL
resource "aws_route53_record" "site" {
  zone_id = var.zone_id
  name    = var.domain_name
  type    = "A"

  alias {
    name                   = aws_cloudfront_distribution.site.domain_name
    zone_id                = aws_cloudfront_distribution.site.hosted_zone_id
    evaluate_target_health = false
  }
}

output "site_url" {
  value = "https://${var.domain_name}"
}

Step 6: upload the files

The website files are objects too. Walk the site/ folder with fileset() and map file extensions to content types, so browsers render each file correctly:

HCL
locals {
  content_types = {
    html = "text/html"
    css  = "text/css"
    js   = "application/javascript"
    svg  = "image/svg+xml"
    png  = "image/png"
    json = "application/json"
  }
  files = fileset(var.site_dir, "**")
}

resource "aws_s3_object" "files" {
  for_each     = local.files
  bucket       = aws_s3_bucket.site.id
  key          = each.value
  source       = "${var.site_dir}/${each.value}"
  etag         = filemd5("${var.site_dir}/${each.value}")
  content_type = lookup(local.content_types, reverse(split(".", each.value))[0], "application/octet-stream")
}

The etag makes Terraform re-upload a file only when its content changes. The program below reproduces the type-mapping logic on a sample file list.

Python Which files get which content type?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The application/octet-stream fallback makes browsers download a file instead of showing it, so a missing map entry is a visible bug. Add woff2 and txt to the map.

Invalidating the cache

CloudFront caches files at the edge. After you change a page, either use versioned file names (app.3f2a.js) or invalidate paths with the CLI in your deploy pipeline: aws cloudfront create-invalidation --distribution-id ID --paths "/*". Avoid managing invalidations in Terraform; they are events, not infrastructure.

Validate the design

Python Design checklist

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extensions to try

  1. Move the stack into a reusable module with domain_name and site_dir inputs (Modules).
  2. Add a www alias and redirect.
  3. Add CloudFront access logs to a second private bucket with a lifecycle rule.
  4. Deploy from CI: plan on pull request, apply on merge (CI lesson).

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. How can CloudFront read a private bucket?

    OAC uses SigV4 signing, and the policy condition limits access to the distribution ARN.
  2. 2. Why does this project use a second aws provider with alias us_east_1?

    ACM certificates used by CloudFront must live in N. Virginia.
  3. 3. What does the etag argument on aws_s3_object achieve?

    filemd5 changes with the content, so Terraform sees a diff exactly when needed.
  4. 4. What happens to a file whose extension is missing from the content-type map?

    The lookup default is octet-stream; add the extension to the map.

Summary

  • A private S3 bucket behind CloudFront with origin access control is the standard secure static hosting design.
  • Certificates for CloudFront live in us-east-1; use a provider alias.
  • DNS validation and certificate validation resources make Terraform wait until the certificate is ready.
  • fileset(), for_each, filemd5() and a content-type map upload a whole site idempotently.
  • Handle cache invalidation in your deploy pipeline, not in Terraform.

Next: Project: A Three-Tier App from Modules

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.