Skip to main content

CloudFront Distribution Module

Deploy an AWS CloudFront CDN distribution with configurable origins, cache behaviors, and DDoS protection.

What You'll Build

  • CloudFront distribution with one or more origins
  • Cache behaviors with origin request policies
  • SSL/TLS certificate binding
  • Origin access identity (OAI) for S3 origins
  • Optional AWS WAF integration

How to Use

module "cloudfront" {
source = "github.com/nnthanh101/terraform-aws/modules/cloudfront"

enabled = true
comment = "CDN for app assets"
aliases = ["cdn.example.com"]

origin = {
s3 = {
domain_name = aws_s3_bucket.assets.bucket_regional_domain_name
origin_id = "S3"
s3_origin_config = {
origin_access_identity = aws_cloudfront_origin_access_identity.this.cloudfront_access_identity_path
}
}
}

default_cache_behavior = {
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
target_origin_id = "S3"
compress = true
viewer_protocol_policy = "redirect-to-https"

cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
origin_request_policy_id = data.aws_cloudfront_origin_request_policy.cors.id
}

viewer_certificate = {
cloudfront_default_certificate = true
}

tags = {
Environment = "prod"
Service = "cdn"
}
}

Key Variables

VariableTypePurpose
enabledboolEnable/disable distribution
aliaseslist(string)CNAME domains (e.g., cdn.example.com)
commentstringHuman-readable description
originmap(object)Origin backends (S3, ALB, custom HTTP)
default_cache_behaviorobjectDefault cache and routing rules
ordered_cache_behaviorslist(object)Additional path-based behaviors
viewer_certificateobjectSSL/TLS cert (ACM or CloudFront default)
restrictionsobjectGeo-blocking, IP restrictions

Outputs

OutputUse Case
distribution_idUsed in CloudFront invalidation requests
domain_nameCloudFront domain (*.cloudfront.net)
etagCurrent distribution version tag

Integration

  • S3: Serve static assets with OAI for secure origin access
  • ALB: Cache HTTP API responses from load balancer
  • Route53: CNAME alias pointing to CloudFront domain
  • ACM: Bind SSL/TLS certificate to distribution
  • WAF: Attach Web ACL for DDoS/attack mitigation

Source Reference

Module: terraform-aws/modules/cloudfront