bashadvanced
Terraform — AWS S3 + CloudFront Static Site
Provision an S3 static website with CloudFront CDN, SSL certificate, and origin access control.
bashPress ⌘/Ctrl + Shift + C to copy
# main.tf — S3 + CloudFront static site
provider "aws" {
region = "us-east-1"
}
resource "aws_s3_bucket" "site" {
bucket = "my-static-site-${random_id.suffix.hex}"
}
resource "random_id" "suffix" {
byte_length = 4
}
resource "aws_s3_bucket_website_configuration" "site" {
bucket = aws_s3_bucket.site.id
index_document { suffix = "index.html" }
error_document { key = "404.html" }
}
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"
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 {
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
target_origin_id = "s3-site"
viewer_protocol_policy = "redirect-to-https"
compress = true
forwarded_values {
query_string = false
cookies { forward = "none" }
}
}
restrictions {
geo_restriction { restriction_type = "none" }
}
viewer_certificate {
cloudfront_default_certificate = true
}
}
output "cloudfront_url" {
value = aws_cloudfront_distribution.site.domain_name
}Use Cases
- Deploying static sites with global CDN distribution
- Infrastructure-as-code for AWS hosting
- Automated SSL and origin access control setup
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
AWS SDK v3 — S3 Operations in TypeScript
Perform S3 operations with AWS SDK v3: upload, download, list, presigned URLs, and multipart upload.
Best for: Server-side file uploads to S3
#aws#s3
bashadvanced
Terraform AWS EC2 Instance Setup
Terraform configuration to provision an EC2 instance with VPC, security group, and SSH key pair.
Best for: Provisioning cloud infrastructure with code
#terraform#aws
bashadvanced
Terraform Aws
DevOps practice: terraform-aws
Best for: infrastructure management
#devops#infrastructure
bashadvanced
Aws Cdk
DevOps practice: aws-cdk
Best for: infrastructure management
#devops#infrastructure