rvn-cloudfront / Latest version: 1.9.0
Dependencies and consumers
Every dependency input can be specified manually to reference existing external infrastructure rather than a Ravion module. Set the dependency input tonull and set its mapped inputs directly; see Use existing infrastructure instead of a module reference.
Readme
CloudFront distribution that serves web applications and private S3 buckets from ECS services, standalone ALBs, S3 origins, and other custom origins.Overview
The CloudFront module puts the AWS CloudFront edge network in front of a dynamic web application or private S3 bucket. Point it at an existing ECS web service, an ECS cluster load balancer, a standalone ALB, an S3 bucket, or any custom domain, and Ravion provisions the distribution, origin configuration, cache behaviors, optional access logging bucket, and metrics. The default configuration is safe for dynamic apps: responses are cached at the edge only when your app returns Cache-Control headers, and the full viewer request, including the Host header, cookies, and query strings, is forwarded to the origin. You get TLS termination close to users, HTTP/2 and HTTP/3, connection reuse to the origin, optional WAF, and per-path caching for static assets. Terraform source: ravionhq/modules/cdn/cloudfrontUse cases
How load balancer connections work
ECS and standalone ALBs route requests using listener rules that match the request’s host and path. CloudFront preserves that behavior: the default origin request policy (AWS managed AllViewerAndCloudFrontHeaders-2022-06) forwards the viewer’s Host header to the load balancer, so the same listener rules keep routing each request to the right service. It also forwards CloudFront-Viewer-Country and other CloudFront headers. That means the origin is really the load balancer, not an individual service:
Both ECS options resolve to the same ALB when the service runs on that cluster, so pick whichever is easier to select. A standalone ALB can be selected directly when it is managed by the rvn-aws-alb module. One distribution can front all services behind the load balancer.
Domain aliases and host routing
If your services route by Domain host rules, the forwarded Host header must match those rules:- Add each domain to Domain aliases (for example app.example.com and api.example.com).
- Point the domains’ DNS at the CloudFront distribution domain.
- Keep the same domains in the ECS services’ Domain host rules.
Origin custom headers
Origin custom headers are added to every request CloudFront sends to the configured origin. The primary custom or load balancer origin and each additional origin can have their own headers. They can provide a shared value for an ALB listener rule, allowing the origin to route requests only when they came through this distribution. Configure the matching header name and value on the ALB rule separately. Do not use the viewerHost header as the shared value. Choose a dedicated header name, use a different value for each protected service or distribution, and rotate the value if it is exposed. The configured value is part of the module configuration, so do not treat it as a general-purpose application secret.
TLS between CloudFront and the origin
Origin protocol policy defaults to HTTPS only. For that to work, the load balancer must have an HTTPS listener with a certificate that is valid for the forwarded Host domain, which is the same certificate the ALB already needs to serve those domains directly. Use HTTP only when the load balancer has no HTTPS listener; traffic from CloudFront to the origin is then unencrypted.Private S3 origins
S3 origins use CloudFront Origin Access Control so the bucket can stay private. Use the None origin request policy unless you intentionally need CORS headers, because forwarding the viewer Host header to S3 can break OAC-signed origin requests. The bucket policy must allow CloudFront to read objects, scoped to this distribution ARN. For rvn-s3 buckets, apply the CloudFront stack first, then edit the S3 bucket and add the CloudFront OAC read policy template with the CloudFront distribution ARN.Signed URLs
Enable Require signed URLs to set trusted key groups on the default cache behavior. Each custom cache behavior can also require signed URLs for only that path and must provide its own trusted key group IDs. Ravion does not create key groups in this module; provide existing CloudFront key group IDs and keep the private signing key in your application.Edge redirects
Redirect rules run at viewer request time before CloudFront checks its cache or contacts an origin. Rules are evaluated in order and the first match wins. Sources and destinations accept absolute HTTPS URLs or host-agnostic paths. Use:name to capture one path segment and a final :name* to capture the remaining path, then place those named values anywhere in the destination. Query preservation is optional and disabled by default.
The managed viewer-request function is attached to the default cache behavior and every custom cache behavior when redirect rules are configured. CloudFront allows only one viewer-request edge association per behavior, so redirects cannot be combined with a viewer-request CloudFront Function or Lambda@Edge association supplied through Advanced Terraform variables.
The module prevents a rule from redirecting back into its own source pattern. It cannot detect cycles spanning multiple independently matching rules, so review rule ordering and destinations when defining bidirectional or multi-domain redirects.
Avoid overlapping same-host rules
Before returning a redirect, the edge function checks whether the destination would match the same source pattern on the same host. If it would, the function skips that rule and evaluates the next rule. If no later rule matches, CloudFront sends the original request to the configured origin. This prevents an infinite loop, but it can make an overlapping rule appear inactive. For example, a source ofhttps://example.cloudfront.net/:path* and destination of https://example.cloudfront.net/docs/:path* does not redirect. The destination /docs/guide still matches the broad source and would otherwise become /docs/docs/guide on the next request.
Use different hosts for a domain migration, such as https://docs.example.com/:path* to https://www.example.com/docs/:path*. For same-host testing, use non-overlapping namespaces such as https://example.cloudfront.net/old/:path* to https://example.cloudfront.net/docs/:path*. To redirect only the root, use the exact source https://example.cloudfront.net without a path parameter.
Redirect patterns do not currently support exclusions such as “all paths except /docs”.
Certificates
Domain aliases require a certificate issued in us-east-1, because CloudFront is a global service. Select an ACM Certificate module instance in the ACM certificate field; its certificate ARN is mapped automatically. In that certificate’s Domains list, put the primary domain first and add any other aliases after it. This certificate is for viewers connecting to CloudFront. The load balancer keeps its own regional certificate for the origin leg.Caching
The default cache behavior applies to all requests that do not match a custom cache behavior path:
With the recommended cache policy, nothing is cached until the app opts in by returning Cache-Control headers such as public, max-age=300. Responses without caching headers always go to the origin. The cache key includes query strings, and the origin request policy controls what else reaches the origin. Both AllViewer and AllViewerAndCloudFrontHeaders-2022-06 preserve the viewer Host header for load balancer listener rules. Choose CachingDisabled to turn off edge caching entirely, or CachingOptimized to cache aggressively regardless of origin headers. Pick Custom policy ID to use a cache policy you created in your own account.
Forwarding CloudFront-Viewer-Country does not add it to the cache key. If your app returns country-specific content, such as geo pricing, choose CachingDisabled or a custom cache policy that includes CloudFront-Viewer-Country to avoid serving one country’s response to another.
New instances use AllViewerAndCloudFrontHeaders-2022-06 starting with version 1.5.0. Existing instances keep their saved origin request policy; select this policy explicitly to forward viewer country. For private S3 origins with OAC, continue to use None instead.
Response headers policy is optional and adds headers such as the SecurityHeadersPolicy set or CORS headers to every response.
To cache static content, add Custom cache behaviors. A typical setup adds /assets/* or /static/* with the CachingOptimized policy and GET, HEAD methods. Each behavior can also target an additional origin for path-based traffic splitting. Per-behavior policies use the managed policy lists; for a custom per-path policy, override ordered_cache_behaviors in Advanced Terraform variables.
CloudFront accepts only three allowed-method combinations per behavior: GET,HEAD; GET,HEAD,OPTIONS; or all seven methods.
Distribution settings
Monitoring
The dashboard always shows the default CloudFront distribution metrics: requests, total error rate, 4xx error rate, 5xx error rate, bytes downloaded, and bytes uploaded. CloudFront publishes these default metrics to CloudWatch at no additional CloudWatch metric cost. You can also enable all additional metrics charts for cache hit rate, origin latency, and per-status error rates. AWS enables all 8 additional metrics together and CloudWatch charges a flat per-metric monthly rate, about $2.40 per month per distribution at the standard $0.30 per metric rate. This cost does not change with request volume.Access logging
CloudFront access logging is on by default, delivered to CloudWatch Logs and viewable in Ravion. Choose where logs are delivered:
Logging retention days defaults to 365 and controls the CloudWatch log group retention or the S3 bucket lifecycle expiry, depending on the destination. CloudWatch retention must be one of the standard CloudWatch Logs retention values (1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, and larger).
Static IPs
Static IPs are disabled by default. Choose Create a static IP list to allocate 3 IPv4 addresses for apex DNS A records or 21 for firewall allowlisting. Choose Use an existing static IP list to share a list in the same AWS account and avoid another allocation charge. AWS approval is required before creating a list. Static IPs use all edge locations and disable viewer IPv6. HTTPS still uses your domain name, not a bare IP address. AWS charges $0.005 per IPv4 address/hour: about $11/month for 3 or $77/month for 21, plus standard CloudFront usage. The list is billed until deleted. Changing the count replaces the IPs; update external DNS or allowlists afterward. The stack outputs include the created addresses asanycast_ips and the reusable list ID as anycast_ip_list_id. For an existing list, get its addresses from its owning stack. Remove other sites’ references before deleting an owning site’s list.
Configuration
Design decisions
- The primary origin is always the load balancer or domain you select, with the fixed origin ID primary. ECS and ALB references discover an existing load balancer’s DNS name and ARN; they do not create per-service origins, because listener rules already fan traffic out behind one origin.
- Caching is disabled by default. A wrong edge cache on dynamic responses is worse than no cache, so caching is an explicit per-path opt-in.
- The AllViewerAndCloudFrontHeaders-2022-06 origin request policy is the default so apps receive viewer country while Host-based listener rules, cookies, and query strings keep working behind CloudFront.
- Redirects use one managed CloudFront Function shared by the module’s distributions and attached to every cache behavior.
- One module instance manages one distribution. Create additional instances when domains need different edge configuration; they can share the same origin.
- The certificate is referenced from an ACM Certificate module instance so the us-east-1 requirement is explicit and reusable.
Learn more
- Amazon CloudFront developer guide
- Using managed cache and origin request policies
- Requirements for using alternate domain names
- Amazon CloudFront metrics
Inputs reference
All inputs forrvn-cloudfront version 1.9.0. Use the name shown for each field as the input key in module config.
- Inputs — AWS account & region, Distribution, Origin, Edge redirects, Default cache behavior, Signed URLs, Distribution settings, Monitoring, Access logging, Misc, Terraform settings