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
| Variable | Type | Purpose |
|---|---|---|
enabled | bool | Enable/disable distribution |
aliases | list(string) | CNAME domains (e.g., cdn.example.com) |
comment | string | Human-readable description |
origin | map(object) | Origin backends (S3, ALB, custom HTTP) |
default_cache_behavior | object | Default cache and routing rules |
ordered_cache_behaviors | list(object) | Additional path-based behaviors |
viewer_certificate | object | SSL/TLS cert (ACM or CloudFront default) |
restrictions | object | Geo-blocking, IP restrictions |
Outputs
| Output | Use Case |
|---|---|
distribution_id | Used in CloudFront invalidation requests |
domain_name | CloudFront domain (*.cloudfront.net) |
etag | Current 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