Skip to main content

Component: spa-s3-cloudfront

This component is responsible for provisioning:

  • S3 bucket
  • CloudFront distribution for a Single Page Application
  • ACM placed in us-east-1 regardless of the stack region (requirement of CloudFront)

NOTE: The component does not use the ACM created by dns-delegated, because the ACM region has to be us-east-1.


Stack Level: Regional

Here are some example snippets for how to use this component:

An import for all instantiations of the spa-s3-cloudfront component can be created at stacks/spa/spa-defaults.yaml:

# lookup GitHub Runner IAM role via remote state
github_runners_deployment_principal_arn_enabled: true
github_runners_component_name: github-runners
github_runners_tenant_name: core
github_runners_environment_name: ue2
github_runners_stage_name: auto
origin_force_destroy: false
origin_versioning_enabled: true
origin_block_public_acls: true
origin_block_public_policy: true
origin_ignore_public_acls: true
origin_restrict_public_buckets: true
origin_encryption_enabled: true
cloudfront_index_document: index.html
cloudfront_ipv6_enabled: false
cloudfront_compress: true
cloudfront_default_root_object: index.html
cloudfront_viewer_protocol_policy: redirect-to-https

An import for all instantiations for a specific SPA can be created at stacks/spa/example-spa.yaml:

component: spa-s3-cloudfront
name: example-spa
site_subdomain: example-spa
- error_caching_min_ttl: 1
error_code: 403
response_code: 200
response_page_path: /index.html
cloudfront_default_ttl: 60
cloudfront_min_ttl: 60
cloudfront_max_ttl: 60

Finally, the spa-s3-cloudfront component can be instantiated in a stack config:

- spa/example-spa

component: spa-s3-cloudfront
workspace_enabled: true
vars: {}

Failover Origins

Failover origins are supported via var.failover_s3_origin_name and var.failover_s3_origin_region.

Preview Environments

SPA Preview environments (i.e. mapping to a /subdomain path in the S3 bucket) powered by Lambda@Edge are supported via var.preview_environment_enabled. See the both the variable description and inline documentation for an extensive explanation for how these preview environments work.

Customizing Lambda@Edge

This component supports customizing Lambda@Edge functions for the CloudFront distribution. All Lambda@Edge function configuration is deep merged before being passed to the cloudposse/cloudfront-s3-cdn/aws//modules/lambda@edge module. You can add additional functions and overwrite existing functions as such:

- catalog/spa-s3-cloudfront/defaults

component: spa-s3-cloudfront
- spa-s3-cloudfront-defaults
enabled: true
viewer_request: # overwrite existing function
source: null # this overwrites the 404 viewer request source with deep merging
source_zip: "./dist/"
runtime: "nodejs16.x"
handler: "index.handler"
event_type: "viewer-request"
include_body: false
viewer_response: # new function
source_zip: "./dist/"
runtime: "nodejs16.x"
handler: "index.handler"
event_type: "viewer-response"
include_body: false


terraform>= 1.0.0
aws>= 4.9.0


aws>= 4.9.0
aws.failover>= 4.9.0




aws_iam_policy_document.additional_lambda_edge_permissiondata source
aws_iam_policy_document.github_actions_iam_policydata source
aws_s3_bucket.failover_bucketdata source


additional_tag_mapAdditional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.
attributesID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.
block_origin_public_access_enabledWhen set to 'true' the s3 origin bucket will have public access block enabled.booltrueno
cloudfront_access_log_bucket_nameWhen cloudfront_access_log_create_bucket is false, this is the name of the existing S3 Bucket where
CloudFront Access Logs are to be delivered and is required. IGNORED when cloudfront_access_log_create_bucket is true.
cloudfront_access_log_bucket_name_rendering_enabledIf set to true, then the CloudFront origin access logs bucket name will be rendered by calling format("%v-%v-%v-%v", var.namespace, var.environment, var.stage, var.cloudfront_access_log_bucket_name).
Otherwise, the value for cloudfront_access_log_bucket_name will need to be the globally unique name of the access logs bucket.

For example, if this component produces an origin bucket named eg-ue1-devplatform-example and cloudfront_access_log_bucket_name is set to
example-cloudfront-access-logs, then the bucket name will be rendered to be eg-ue1-devplatform-example-cloudfront-access-logs.
cloudfront_access_log_create_bucketWhen true and cloudfront_access_logging_enabled is also true, this module will create a new,
separate S3 bucket to receive CloudFront Access Logs.
cloudfront_access_log_prefixPrefix to use for CloudFront Access Log object keys. Defaults to no prefix.string""no
cloudfront_access_log_prefix_rendering_enabledWhether or not to dynamically render ${} at the end of var.cloudfront_access_log_prefix.boolfalseno
cloudfront_allowed_methodsList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFront.list(string)
cloudfront_aws_shield_protection_enabledEnable or disable AWS Shield Advanced protection for the CloudFront distribution. If set to 'true', a subscription to AWS Shield Advanced must exist in this account.boolfalseno
cloudfront_aws_waf_component_nameThe name of the component used when deploying WAF ACLstring"waf"no
cloudfront_aws_waf_environmentThe environment where the WAF ACL for CloudFront distribution exists.stringnullno
cloudfront_aws_waf_protection_enabledEnable or disable AWS WAF for the CloudFront distribution.

This assumes that the aws-waf-acl-default-cloudfront component has been deployed to the regional stack corresponding
to var.waf_acl_environment.
cloudfront_cached_methodsList of cached methods (e.g. GET, PUT, POST, DELETE, HEAD).list(string)
cloudfront_compressCompress content for web requests that include Accept-Encoding: gzip in the request header.boolfalseno
cloudfront_custom_error_responseList of one or more custom error response element maps.
error_caching_min_ttl = optional(string, "10")
error_code = string
response_code = string
response_page_path = string
cloudfront_default_root_objectObject that CloudFront return when requests the root URL.string"index.html"no
cloudfront_default_ttlDefault amount of time (in seconds) that an object is in a CloudFront cache.number60no
cloudfront_index_documentAmazon S3 returns this index document when requests are made to the root domain or any of the subfolders.string"index.html"no
cloudfront_ipv6_enabledSet to true to enable an AAAA DNS record to be set as well as the A record.booltrueno
cloudfront_lambda_function_associationA config block that configures the CloudFront distribution with lambda@edge functions for specific events.
event_type = string
include_body = bool
lambda_arn = string
cloudfront_max_ttlMaximum amount of time (in seconds) that an object is in a CloudFront cache.number31536000no
cloudfront_min_ttlMinimum amount of time that you want objects to stay in CloudFront caches.number0no
cloudfront_viewer_protocol_policyLimit the protocol users can use to access content. One of allow-all, https-only, or redirect-to-https.string"redirect-to-https"no
contextSingle object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
custom_originsA list of additional custom website origins for this distribution.
domain_name = string
origin_id = string
origin_path = string
custom_headers = list(object({
name = string
value = string
custom_origin_config = object({
http_port = number
https_port = number
origin_protocol_policy = string
origin_ssl_protocols = list(string)
origin_keepalive_timeout = number
origin_read_timeout = number
delimiterDelimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
descriptor_formatsDescribe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
{<br/> format = string<br/> labels = list(string)<br/>}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).
dns_delegated_environment_nameThe environment where dns-delegated component is deployed tostring"gbl"no
enabledSet to false to prevent the module from creating any resourcesboolnullno
environmentID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'stringnullno
external_aliasesList of FQDN's - Used to set the Alternate Domain Names (CNAMEs) setting on CloudFront. No new Route53 records will be created for these.

Setting process_domain_validation_options to true may cause the component to fail if an external_alias DNS zone is not controlled by Terraform.

Setting preview_environment_enabled to true will cause this variable to be ignored.
failover_criteria_status_codesList of HTTP Status Codes to use as the origin group failover criteria.list(string)
failover_s3_origin_environmentThe fixed name of the AWS Region where the
failover S3 origin exists. Setting this variable will enable use of a failover S3 origin, but it is required for the
failover S3 origin to exist beforehand. This variable is used in conjunction with var.failover_s3_origin_format to
build out the name of the Failover S3 origin in the specified region.

For example, if this component creates an origin of name eg-ue1-devplatform-example and this variable is set to uw1,
then it is expected that a bucket with the name eg-uw1-devplatform-example-failover exists in us-west-1.
failover_s3_origin_formatIf var.failover_s3_origin_environment is supplied, this is the format to use for the failover S3 origin bucket name when
building the name via format([format], var.namespace, var.failover_s3_origin_environment, var.stage,
and then looking it up via the aws_s3_bucket Data Source.

For example, if this component creates an origin of name eg-ue1-devplatform-example and var.failover_s3_origin_environment
is set to uw1, then it is expected that a bucket with the name eg-uw1-devplatform-example-failover exists in us-west-1.
forward_cookiesSpecifies whether you want CloudFront to forward all or no cookies to the origin. Can be 'all' or 'none'string"none"no
forward_header_valuesA list of whitelisted header values to forward to the origin (incompatible with cache_policy_id)list(string)
github_actions_allowed_reposA list of the GitHub repositories that are allowed to assume this role from GitHub Actions. For example,
["cloudposse/infra-live"]. Can contain "*" as wildcard.
If org part of repo name is omitted, "cloudposse" will be assumed.
github_actions_iam_role_attributesAdditional attributes to add to the role namelist(string)[]no
github_actions_iam_role_enabledFlag to toggle creation of an IAM Role that GitHub Actions can assume to access AWS resourcesboolfalseno
github_runners_component_nameThe name of the component that deploys GitHub Runners, used in remote-state lookupstring"github-runners"no
github_runners_deployment_principal_arn_enabledA flag that is used to decide whether or not to include the GitHub Runner's IAM role in origin_deployment_principal_arns listbooltrueno
github_runners_environment_nameThe name of the environment where the CloudTrail bucket is provisionedstring"ue2"no
github_runners_stage_nameThe stage name where the CloudTrail bucket is provisionedstring"auto"no
github_runners_tenant_nameThe tenant name where the GitHub Runners are provisionedstringnullno
id_length_limitLimit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.
label_key_caseControls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.
label_orderThe order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.
label_value_caseControls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.
labels_as_tagsSet of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.
lambda_edge_allowed_ssm_parametersThe Lambda@Edge functions will be allowed to access the list of AWS SSM parameter with these ARNslist(string)[]no
lambda_edge_destruction_delayThe delay, in Golang ParseDuration format, to wait before destroying the Lambda@Edge

This delay is meant to circumvent Lambda@Edge functions not being immediately deletable following their dissociation from
a CloudFront distribution, since they are replicated to CloudFront Edge servers around the world.

If set to null, no delay will be introduced.

By default, the delay is 20 minutes. This is because it takes about 3 minutes to destroy a CloudFront distribution, and
around 15 minutes until the Lambda@Edge function is available for deletion, in most cases.

For more information, see:
lambda_edge_functionsLambda@Edge functions to create.

The key of this map is the name of the Lambda@Edge function.

This map will be deep merged with each enabled default function. Use deep merge to change or overwrite specific values passed by those function objects.
source = optional(list(object({
filename = string
content = string
source_dir = optional(string)
source_zip = optional(string)
runtime = string
handler = string
event_type = string
include_body = bool
lambda_edge_handlerThe default Lambda@Edge handler for all functions.

This value is deep merged in module.lambda_edge_functions with var.lambda_edge_functions and can be overwritten for any individual function.
lambda_edge_runtimeThe default Lambda@Edge runtime for all functions.

This value is deep merged in module.lambda_edge_functions with var.lambda_edge_functions and can be overwritten for any individual function.
nameID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.
namespaceID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally uniquestringnullno
ordered_cacheAn ordered list of cache behaviors resource for this distribution.
List in order of precedence (first match wins). This is in addition to the default cache policy.
Set target_origin_id to "" to specify the S3 bucket origin created by this module.
target_origin_id = string
path_pattern = string

allowed_methods = list(string)
cached_methods = list(string)
compress = bool
trusted_signers = list(string)
trusted_key_groups = list(string)

cache_policy_id = string
origin_request_policy_id = string

viewer_protocol_policy = string
min_ttl = number
default_ttl = number
max_ttl = number
response_headers_policy_id = string

forward_query_string = bool
forward_header_values = list(string)
forward_cookies = string
forward_cookies_whitelisted_names = list(string)

lambda_function_association = list(object({
event_type = string
include_body = bool
lambda_arn = string

function_association = list(object({
event_type = string
function_arn = string
origin_allow_ssl_requests_onlySet to true in order to have the origin bucket require requests to use Secure Socket Layer (HTTPS/SSL). This will explicitly deny access to HTTP requestsbooltrueno
origin_deployment_actionsList of actions to permit origin_deployment_principal_arns to perform on bucket and bucket prefixes (see origin_deployment_principal_arns)list(string)
origin_deployment_principal_arnsList of role ARNs to grant deployment permissions to the origin Bucket.list(string)[]no
origin_encryption_enabledWhen set to 'true' the origin Bucket will have aes256 encryption enabled by default.booltrueno
origin_force_destroyA boolean string that indicates all objects should be deleted from the origin Bucket so that the Bucket can be destroyed without error. These objects are not recoverable.boolfalseno
origin_s3_access_log_bucket_nameName of the existing S3 bucket where S3 Access Logs for the origin Bucket will be delivered. Default is not to enable S3 Access Logging for the origin Bucket.string""no
origin_s3_access_log_bucket_name_rendering_enabledIf set to true, then the S3 origin access logs bucket name will be rendered by calling format("%v-%v-%v-%v", var.namespace, var.environment, var.stage, var.origin_s3_access_log_bucket_name).
Otherwise, the value for origin_s3_access_log_bucket_name will need to be the globally unique name of the access logs bucket.

For example, if this component produces an origin bucket named eg-ue1-devplatform-example and origin_s3_access_log_bucket_name is set to
example-s3-access-logs, then the bucket name will be rendered to be eg-ue1-devplatform-example-s3-access-logs.
origin_s3_access_log_prefixPrefix to use for S3 Access Log object keys. Defaults to logs/${}string""no
origin_s3_access_logging_enabledSet true to deliver S3 Access Logs to the origin_s3_access_log_bucket_name bucket.
Defaults to false if origin_s3_access_log_bucket_name is empty (the default), true otherwise.
Must be set explicitly if the access log bucket is being created at the same time as this module is being invoked.
origin_versioning_enabledEnable or disable versioning for the origin Bucket. Versioning is a means of keeping multiple variants of an object in the same bucket.boolfalseno
parent_zone_nameParent domain name of site to publish. Defaults to format(parent_zone_name_pattern, stage, environment).string""no
preview_environment_enabledEnable or disable SPA Preview Environments via Lambda@Edge, i.e. mapping to the /subdomain
path in the origin S3 bucket.

This variable implicitly affects the following variables:

* cloudfront_lambda_function_association
process_domain_validation_optionsFlag to enable/disable processing of the record to add to the DNS zone to complete certificate validationbooltrueno
regex_replace_charsTerraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.
regionAWS Region.stringn/ayes
s3_object_ownershipSpecifies the S3 object ownership control on the origin bucket. Valid values are ObjectWriter, BucketOwnerPreferred, and 'BucketOwnerEnforced'.string"ObjectWriter"no
s3_website_enabledSet to true to enable the created S3 bucket to serve as a website independently of CloudFront,
and to use that website as the origin.

Setting preview_environment_enabled will implicitly set this to true.
s3_website_password_enabledIf set to true, and s3_website_enabled is also true, a password will be required in the Referrer field of the
HTTP request in order to access the website, and CloudFront will be configured to pass this password in its requests.
This will make it much harder for people to bypass CloudFront and access the S3 website directly via its website endpoint.
site_fqdnFully qualified domain name of site to publish. Overrides site_subdomain and parent_zone_name.string""no
site_subdomainSubdomain to plug into site_name_pattern to make site FQDN.string""no
stageID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'stringnullno
tagsAdditional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno


cloudfront_distribution_aliasCloudfront Distribution Alias Record.
cloudfront_distribution_domain_nameCloudfront Distribution Domain Name.
failover_s3_bucket_nameFailover Origin bucket name, if enabled.
github_actions_iam_role_arnARN of IAM role for GitHub Actions
github_actions_iam_role_nameName of IAM role for GitHub Actions
origin_s3_bucket_arnOrigin bucket ARN.
origin_s3_bucket_nameOrigin bucket name.



Component PRs #991 and #995

Drop lambda_edge_redirect_404

This PRs removes the lambda_edge_redirect_404 functionality because it leads to significat costs. Use native CloudFront error pages configs instead.

- error_code: 404
response_code: 404
response_page_path: /404.html

Components PR #978

Lambda@Edge Submodule Refactor

This PR has significantly refactored how Lambda@Edge functions are managed by Terraform with this component. Previously, the specific use cases for Lambda@Edge functions were handled by submodules lambda-edge-preview and lambda_edge_redirect_404. These component submodules both called the same Terraform module, cloudposse/cloudfront-s3-cdn/aws//modules/lambda@edge. These submodules have been replaced with a single Terraform file,

The reason a single file is better than submodules is (1) simplification and (2) adding the ability to deep merge function configuration. Cloudfront Distributions support a single Lambda@Edge function for each origin/viewer request or response. With deep merging, we can define default values for function configuration and provide the ability to overwrite specific values for a given deployment.

Specifically, our own use case is using an authorization Lambda@Edge viewer request only if the paywall is enabled. Other deployments use an alternative viewer request to redirect 404.

Upgrading with preview_environment_enabled: true or lambda_edge_redirect_404_enabled: true

If you have var.preview_environment_enabled or var.lambda_edge_redirect_404_enabled set to true, Terraform moved will move the previous resource by submodule to the new resource by file. Please give your next Terraform plan a sanity check. Any existing Lambda functions should not be destroyed by this change.

Upgrading with both preview_environment_enabled: false and lambda_edge_redirect_404_enabled: false

If you have no Lambda@Edge functions deployed and where both var.preview_environment_enabled and var.lambda_edge_redirect_404_enabled are false (the default value), no change is necessary.

Lambda Runtime Version

The previous PR #946 introduced the var.lambda_runtime input. Previously, the version of node in both submodules was hard-coded to be nodejs12.x. This PR renames that variable to var.lambda_edge_runtime and sets the default to nodejs16.x.

If you want to maintain the previous version of Node, set var.lambda_edge_runtime to nodejs12.x, though be aware that AWS deprecated that version on March 31, 2023, and lambdas using that environment may no longer work. Otherwise, this component will attempt to deploy the functions with runtime nodejs16.x.