A complete Terraform setup for serving a private S3 bucket through CloudFront: origin access control, the bucket policy, a managed cache policy, an ACM certificate in us-east-1, Route 53 records and invalidations, plus how Encore creates the same from a public bucket declared in code.

Serving files from S3 through CloudFront is one of the most common pieces of AWS infrastructure, and it takes more Terraform than it looks: a private bucket, an origin access control, a distribution, a bucket policy that ties the two together, a certificate in a different region than everything else, DNS records for the custom domain and for certificate validation, and a plan for invalidating cached files.
This guide builds that setup in Terraform piece by piece, explains the parts that usually go wrong, and shows how Encore creates S3 and CloudFront from a public bucket declared in your code, which is infrastructure from code for static and user-uploaded files.
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 6.0"
}
}
}
provider "aws" {
region = "eu-central-1"
}
# CloudFront only accepts ACM certificates from us-east-1.
provider "aws" {
alias = "us_east_1"
region = "us-east-1"
}
variable "domain" {
type = string
default = "assets.example.com"
}
variable "zone_id" {
type = string
}
resource "aws_s3_bucket" "assets" {
bucket_prefix = "app-assets-"
}
resource "aws_s3_bucket_public_access_block" "assets" {
bucket = aws_s3_bucket.assets.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_cloudfront_origin_access_control" "assets" {
name = "app-assets"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
data "aws_cloudfront_cache_policy" "optimized" {
name = "Managed-CachingOptimized"
}
resource "aws_acm_certificate" "assets" {
provider = aws.us_east_1
domain_name = var.domain
validation_method = "DNS"
}
resource "aws_route53_record" "cert_validation" {
for_each = {
for o in aws_acm_certificate.assets.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 = 300
}
resource "aws_acm_certificate_validation" "assets" {
provider = aws.us_east_1
certificate_arn = aws_acm_certificate.assets.arn
validation_record_fqdns = [for r in aws_route53_record.cert_validation : r.fqdn]
}
resource "aws_cloudfront_distribution" "assets" {
enabled = true
is_ipv6_enabled = true
aliases = [var.domain]
price_class = "PriceClass_100"
origin {
origin_id = "s3-assets"
domain_name = aws_s3_bucket.assets.bucket_regional_domain_name
origin_access_control_id = aws_cloudfront_origin_access_control.assets.id
}
default_cache_behavior {
target_origin_id = "s3-assets"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
compress = true
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
acm_certificate_arn = aws_acm_certificate_validation.assets.certificate_arn
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.2_2021"
}
}
# Only this distribution may read the bucket.
data "aws_iam_policy_document" "assets" {
statement {
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.assets.arn}/*"]
principals {
type = "Service"
identifiers = ["cloudfront.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "AWS:SourceArn"
values = [aws_cloudfront_distribution.assets.arn]
}
}
}
resource "aws_s3_bucket_policy" "assets" {
bucket = aws_s3_bucket.assets.id
policy = data.aws_iam_policy_document.assets.json
}
resource "aws_route53_record" "assets" {
for_each = toset(["A", "AAAA"])
zone_id = var.zone_id
name = var.domain
type = each.key
alias {
name = aws_cloudfront_distribution.assets.domain_name
zone_id = aws_cloudfront_distribution.assets.hosted_zone_id
evaluate_target_health = false
}
}
output "url" {
value = "https://${var.domain}"
}
terraform validate passes on this with AWS provider 6.x, and the sections below explain each part.
The bucket keeps all four Block Public Access settings on, and CloudFront reaches it with an origin access control that signs every request with SigV4. AWS recommends OAC over the legacy origin access identity, which does not support buckets in all regions, including opt-in regions, or objects encrypted with SSE-KMS. Older tutorials that use aws_cloudfront_origin_access_identity or a website endpoint origin still work, but leave either a legacy identity or a public bucket behind.
The origin uses bucket_regional_domain_name, not the website endpoint, since OAC only signs requests to the S3 REST endpoint. The bucket policy then grants s3:GetObject to the cloudfront.amazonaws.com service principal with an AWS:SourceArn condition on this distribution's ARN, so another distribution in another account cannot read the bucket by pointing at it. If objects are encrypted with a customer managed KMS key, the key policy needs a matching statement that allows CloudFront to decrypt.
Instead of the legacy forwarded_values block, the cache behavior references the managed Managed-CachingOptimized policy, looked up by name, which caches by path with long default TTLs and handles gzip and Brotli. For files whose names change when their content changes, such as app.3f9a1c.js, that is all you need: new files get new URLs, and nothing has to be invalidated. For files that keep their names, either set a shorter Cache-Control: max-age on the objects when uploading them, which CloudFront respects within the policy's bounds, or invalidate after a change:
Add an output "distribution_id" { value = aws_cloudfront_distribution.assets.id } for that command. Invalidations are billed per path beyond a monthly free allowance, so a wildcard path like /products/*, which counts as a single path, is usually cheaper than listing every file.
CloudFront requires the certificate for a custom domain to be in ACM in us-east-1, whatever region the bucket is in, according to the CloudFront certificate requirements, so the configuration has a second aws provider aliased to us_east_1 and uses it for the certificate and its validation, while the DNS records for validation go into the Route 53 zone as usual. aws_acm_certificate_validation waits until the certificate is issued, so the distribution does not try to use it early, and sni-only with TLSv1.2_2021 avoids the dedicated IP charge and old TLS versions.
The domain itself gets both A and AAAA alias records, since the distribution has IPv6 enabled. PriceClass_100 serves from North America and Europe edge locations only, which costs less if your users are mostly there. AWS also offers flat-rate CloudFront plans, starting at $0 a month, that bundle the CDN with WAF, DNS and a certificate as an alternative to pay-as-you-go pricing, according to the CloudFront pricing page.
Encore brings infrastructure from code to AWS: a bucket is a declaration in the service that uses it, and Public: true makes it a public bucket. According to the AWS infrastructure docs, Encore creates a dedicated S3 bucket with a unique name for it, integrates it with CloudFront and gives each bucket its own domain name. Encore provisions an IAM role for the service, or a service account on GCP. On GCP the same declaration becomes Cloud Storage behind Cloud CDN.
Run in your terminal to get started locally.
// media/media.go
package media
import (
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"path"
"strconv"
"strings"
"time"
"encore.dev"
"encore.dev/beta/auth"
"encore.dev/beta/errs"
"encore.dev/storage/objects"
)
// Public bucket: on AWS, S3 served through CloudFront; on GCP, Cloud Storage behind Cloud CDN.
var images = objects.NewBucket("product-images", objects.BucketConfig{Public: true})
var allowed = map[string]bool{"image/png": true, "image/jpeg": true, "image/webp": true}
const maxBytes = 5 << 20
var secrets struct {
SessionKey string
}
//encore:authhandler
func AuthHandler(ctx context.Context, token string) (auth.UID, error) {
uid, err := userIDFromToken(token)
if err != nil {
return "", &errs.Error{Code: errs.Unauthenticated, Message: "invalid token"}
}
return uid, nil
}
// userIDFromToken verifies a signed access token of the form "<id>.<unix-expiry>.<hex hmac>".
// In production, verify a JWT against your IdP JWKS (signature, issuer, audience,
// expiry) and return the subject.
func userIDFromToken(token string) (auth.UID, error) {
if secrets.SessionKey == "" {
return "", errors.New("auth secret not set")
}
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", errors.New("invalid token")
}
id, expStr, sig := parts[0], parts[1], parts[2]
if id == "" || strings.ContainsAny(id, "/ \t\n") {
return "", errors.New("invalid token")
}
exp, err := strconv.ParseInt(expStr, 10, 64)
if err != nil || exp <= time.Now().Unix() {
return "", errors.New("invalid token")
}
mac := hmac.New(sha256.New, []byte(secrets.SessionKey))
mac.Write([]byte(id + "." + expStr))
expected := hex.EncodeToString(mac.Sum(nil))
if subtle.ConstantTimeCompare([]byte(sig), []byte(expected)) != 1 {
return "", errors.New("invalid token")
}
return auth.UID(id), nil
}
// Upload streams the request body into the caller's prefix and returns its CDN URL.
//
//encore:api auth raw method=PUT path=/images/:name
func Upload(w http.ResponseWriter, req *http.Request) {
uid, ok := auth.UserID()
if !ok {
errs.HTTPError(w, &errs.Error{Code: errs.Unauthenticated, Message: "unauthenticated"})
return
}
name := path.Base(encore.CurrentRequest().PathParams.Get("name"))
if name == "." || name == "/" || strings.HasPrefix(name, ".") {
errs.HTTPError(w, &errs.Error{Code: errs.InvalidArgument, Message: "invalid file name"})
return
}
limited := http.MaxBytesReader(w, req.Body, maxBytes)
head := make([]byte, 512)
n, err := io.ReadFull(limited, head)
if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
errs.HTTPError(w, &errs.Error{Code: errs.InvalidArgument, Message: "upload failed or larger than 5 MiB"})
return
}
ctype := http.DetectContentType(head[:n])
if !allowed[ctype] {
errs.HTTPError(w, &errs.Error{Code: errs.InvalidArgument, Message: "only png, jpeg and webp are accepted"})
return
}
key := fmt.Sprintf("products/%s/%d-%s", uid, time.Now().UnixNano(), name)
up := images.Upload(req.Context(), key, objects.WithUploadAttrs(objects.UploadAttrs{
ContentType: ctype,
}))
if _, err := up.Write(head[:n]); err != nil {
up.Abort(err)
errs.HTTPError(w, err)
return
}
if _, err := io.Copy(up, limited); err != nil {
up.Abort(err)
errs.HTTPError(w, &errs.Error{Code: errs.InvalidArgument, Message: "upload failed or larger than 5 MiB"})
return
}
if err := up.Close(); err != nil {
errs.HTTPError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(map[string]string{"url": images.PublicURL(key).String()})
}
With encore run, a PNG upload returns 201 and a URL on the local bucket that serves the file with image/png, a text upload gets a 400, a 6 MB upload is rejected and nothing is stored, and a file name like .env is refused. In an AWS environment, PublicURL returns the object's URL on the bucket's CloudFront domain instead, so the same code hands out CDN URLs without a distribution ID or domain in config. The object storage docs cover listing, removing and signed URLs for private buckets.
A coding agent that needs another public bucket, say for user avatars, declares it in a line, and the deploy creates its bucket and CloudFront setup, instead of the agent copying the Terraform above and getting the OAC, bucket policy or us-east-1 provider wrong.
Best fit: teams that want public files served through CloudFront from buckets declared in their backend code.
Write the CloudFront Terraform yourself when the distribution does more than serve one bucket: several origins with path-based behaviors, such as /api/* to a load balancer and everything else to S3, CloudFront Functions or Lambda@Edge for redirects and headers, signed URLs or cookies with your own key groups, WAF rules, or a custom domain that has to sit in an existing Route 53 setup. Those are distribution-level decisions that belong in your infrastructure code.
Create a private S3 bucket with Block Public Access, an aws_cloudfront_origin_access_control with signing_behavior always and sigv4, and an aws_cloudfront_distribution whose origin uses the bucket's regional domain name and the OAC ID. Then add an aws_s3_bucket_policy that allows s3:GetObject to the cloudfront.amazonaws.com service principal with an AWS:SourceArn condition on the distribution's ARN.
Use origin access control. AWS recommends OAC over the legacy origin access identity because OAI does not support S3 buckets in every region, including opt-in regions, or server-side encryption with KMS. With OAC, the bucket policy grants the CloudFront service principal access, scoped to one distribution with an AWS:SourceArn condition.
CloudFront only uses ACM certificates from the us-east-1 region. Create the aws_acm_certificate with a provider aliased to us-east-1, validate it with DNS records, and pass the validated certificate ARN to viewer_certificate with ssl_support_method sni-only.
With Encore, declare a bucket with Public: true in Go or TypeScript. On AWS, Encore creates the S3 bucket and integrates it with CloudFront, and the code gets each object's CDN URL from the bucket's PublicURL method, with no distribution, OAC or bucket policy to write.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.