Module: cloudfront-s3-cdn
Terraform module to provision an AWS CloudFront CDN with an S3 origin.
Usage
For a complete example, see examples/complete.
For automated tests of the complete example using bats and Terratest (which tests and deploys the example on AWS), see test.
The following will create a new s3 bucket eg-prod-app
for a cloudfront cdn, and allow principal1
to upload to
prefix1
and prefix2
, while allowing principal2
to manage the whole bucket.
module "cdn" {
source = "cloudposse/cloudfront-s3-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "prod"
name = "app"
aliases = ["assets.cloudposse.com"]
dns_alias_enabled = true
parent_zone_name = "cloudposse.com"
deployment_principal_arns = {
"arn:aws:iam::123456789012:role/principal1" = ["prefix1/", "prefix2/"]
"arn:aws:iam::123456789012:role/principal2" = [""]
}
}
The following will reuse an existing s3 bucket eg-prod-app
for a cloudfront cdn.
module "cdn" {
source = "cloudposse/cloudfront-s3-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
origin_bucket = "eg-prod-app"
aliases = ["assets.cloudposse.com"]
dns_alias_enabled = true
parent_zone_name = "cloudposse.com"
name = "eg-prod-app"
}
The following will create an Origin Group with the origin created by this module as a primary origin and an additional S3 bucket as a failover origin.
module "s3_bucket" {
source = "cloudposse/s3-bucket/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
attributes = ["failover-assets"]
}
module "cdn" {
source = "cloudposse/cloudfront-s3-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
aliases = ["assets.cloudposse.com"]
dns_alias_enabled = true
parent_zone_name = "cloudposse.com"
s3_origins = [{
domain_name = module.s3_bucket.bucket_regional_domain_name
origin_id = module.s3_bucket.bucket_id
origin_path = null
s3_origin_config = {
origin_access_identity = null # will get translated to the origin_access_identity used by the origin created by this module.
}
}]
origin_groups = [{
primary_origin_id = null # will get translated to the origin id of the origin created by this module.
failover_origin_id = module.s3_bucket.bucket_id
failover_criteria = [
403,
404,
500,
502
]
}]
}
Background on CDNs, "Origins", S3 Buckets, and Web Servers
CDNs and Origin Servers
There are some settings you need to be aware of when using this module. In order to understand the settings, you need to understand some of the basics of CDNs and web servers, so we are providing this highly simplified explanation of how they work in order for you to understand the implications of the settings you are providing.
A "CDN" (Content Distribution Network) is a collection of servers scattered around the internet with the aim of making it faster for people to retrieve content from a website. The details of why that is wanted/needed are beyond the scope of this document, as are most of the details of how a CDN is implemented. For this discussion, we will simply treat a CDN as a set of web servers all serving the same content to different users.
In a normal web server (again, greatly simplified), you place files on the server and the web server software receives requests from browsers and responds with the contents of the files.
For a variety of reasons, the web servers in a CDN do not work the way normal web servers work. Instead of getting their content from files on the local server, the CDN web servers get their content by acting like web browsers (proxies). When they get a request from a browser, they make the same request to what is called an "Origin Server". It is called an origin server because it serves the original content of the website, and thus is the origin of the content.
As a website publisher, you put content on an Origin Server (which users usually should be prevented from accessing) and configure your CDN to use your Origin Server. Then you direct users to a URL hosted by your CDN provider, the users' browsers connect to the CDN, the CDN gets the content from your Origin Server, your Origin Server gets the content from a file on the server, and the data gets sent back hop by hop to the user. (The reason this ends up being a good idea is that the CDN can cache the content for a while, serving multiple users the same content while only contacting the origin server once.)
S3 Buckets: file storage and web server
S3 buckets were originally designed just to store files, and they are still most often used for that. The have a lot of access controls to make it possible to strictly limit who can read what files in the bucket, so that companies can store sensitive information there. You may have heard of a number of "data breaches" being caused by misconfigured permissions on S3 buckets, making them publicly accessible. As a result of that, Amazon has some extra settings on top of everything else to keep S3 buckets from being publicly accessible, which is usually a good thing.
However, at some point someone realized that since these files were in the cloud, and Amazon already had these web servers running to provide access to the files in the cloud, it was only a tiny leap to turn an S3 bucket into a web server. So now S3 buckets can be published as websites with a few configuration settings, including making the contents publicly accessible.
Web servers, files, and the different modes of S3 buckets
In the simplest websites, the URL "path" (the part after the site name) corresponds directly to the path (under
a special directory we will call /webroot
) and name
of a file on the web server. So if the web server gets a request for "http://example.com/foo/bar/baz.html" it will
look for a file /webroot/foo/bar/baz.html
. If it exists, the server will return its contents, and if it does not exist,
the server will return a Not Found
error. An S3 bucket, whether configured as a file store or a website, will
always do both of these things.
Web servers, however, do some helpful extra things. To name a few:
- If the URL ends with a
/
, as inhttp://example.com/foo/bar/
, the web server (depending on how it is configured) will either return a list of files in the directory or it will return the contents of a file in the directory with a special name (by default,index.html
) if it exists. - If the URL does not end with a
/
but the last part, instead of being a file name, is a directory name, the web server will redirect the user to the URL with the/
at the end instead of saying the file wasNot Found
. This redirect will get you to theindex.html
file we just talked about. Given the way people pass URLs around, this turns out to be quite helpful. - If the URL does not point to a directory or a file, instead of just sending back a cryptic
Not Found
error code, it can return the contents of a special file called an "error document".
Your Critical Decision: S3 bucket or website?
All of this background is to help you decide how to set website_enabled
and s3_website_password_enabled
.
The default for website_enabled
is false
which is the easiest to configure and the most secure, and with
this setting, s3_website_password_enabled
is ignored.
S3 buckets, in file storage mode (website_enabled = false
), do none of these extra things that web servers do.
If the URL points to a file, it will return the file, and if it does not exactly match a file, it will return
Not Found
. One big advantage, though, is that the S3 bucket can remain private (not publicly accessible). A second,
related advantage is that you can limit the website to a portion of the S3 bucket (everything under a certain prefix)
and keep the contents under the the other prefixes private.
S3 buckets configured as static websites (website_enabled = true
), however, have these extra web server features like redirects, index.html
,
and error documents. The disadvantage is that you have to make the entire bucket public (although you can still
restrict access to some portions of the bucket).
Another feature or drawback (depending on your point of view) of S3 buckets configured as static websites is that
they are directly accessible via their website endpoint
as well as through Cloudfront. This module has a feature, s3_website_password_enabled
, that requires a password
be passed in the HTTP request header and configures the CDN to do that, which will make it much harder to access
the S3 website directly. So set s3_website_password_enabled = true
to limit direct access to the S3 website
or set it to false if you want to be able to bypass Cloudfront when you want to.
In addition to setting website_enabled=true
, you must also:
- Specify at least one
aliases
, like["example.com"]
or["example.com", "www.example.com"]
- Specify an ACM certificate
Custom Domain Names and Generating a TLS Certificate with ACM
When you set up Cloudfront, Amazon will generate a domain name for your website. You amost certainly will not want to publish that. Instead, you will want to use a custom domain name. This module refers to them as "aliases".
To use the custom domain names, you need to
- Pass them in as
aliases
so that Cloudfront will respond to them with your content - Create CNAMEs for the aliases to point to the Cloudfront domain name. If your alias domains are hosted by
Route53 and you have IAM permissions to modify them, this module will set that up for you if you set
dns_alias_enabled = true
. - Generate a TLS Certificate via ACM that includes the all the aliases and pass the ARN for the
certificate in
acm_certificate_arn
. Note that for Cloudfront, the certificate has to be provisioned in theus-east-1
region regardless of where any other resources are.
# For cloudfront, the acm has to be created in us-east-1 or it will not work
provider "aws" {
region = "us-east-1"
alias = "aws.us-east-1"
}
# create acm and explicitly set it to us-east-1 provider
module "acm_request_certificate" {
source = "cloudposse/acm-request-certificate/aws"
providers = {
aws = aws.us-east-1
}
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
domain_name = "example.com"
subject_alternative_names = ["a.example.com", "b.example.com", "*.c.example.com"]
process_domain_validation_options = true
ttl = "300"
}
module "cdn" {
source = "cloudposse/cloudfront-s3-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "prod"
name = "app"
aliases = ["assets.cloudposse.com"]
dns_alias_enabled = true
parent_zone_name = "cloudposse.com"
acm_certificate_arn = module.acm_request_certificate.arn
depends_on = [module.acm_request_certificate]
}
Or use the AWS cli to request new ACM certifiates (requires email validation)
aws acm request-certificate --domain-name example.com --subject-alternative-names a.example.com b.example.com *.c.example.com
NOTE:
Although AWS Certificate Manager is supported in many AWS regions, to use an SSL certificate with CloudFront, it should be requested only in US East (N. Virginia) region.
If you want to require HTTPS between viewers and CloudFront, you must change the AWS region to US East (N. Virginia) in the AWS Certificate Manager console before you request or import a certificate.
https://docs.aws.amazon.com/acm/latest/userguide/acm-regions.html
To use an ACM Certificate with Amazon CloudFront, you must request or import the certificate in the US East (N. Virginia) region. ACM Certificates in this region that are associated with a CloudFront distribution are distributed to all the geographic locations configured for that distribution.
This is a fundamental requirement of CloudFront, and you will need to request the certificate in us-east-1
region.
If there are warnings around the outputs when destroying using this module.
Then you can use this method for supressing the superfluous errors.
TF_WARN_OUTPUT_ERRORS=1 terraform destroy
Lambda@Edge
This module also features a Lambda@Edge submodule. Its lambda_function_association
output is meant to feed directly into the variable of the same name in the parent module.
provider "aws" {
region = var.region
}
provider "aws" {
region = "us-east-1"
alias = "us-east-1"
}
module "lambda_at_edge" {
source = "cloudposse/cloudfront-s3-cdn/aws//modules/lambda@edge"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
functions = {
origin_request = {
source = [{
content = <<-EOT
'use strict';
exports.handler = (event, context, callback) => {
//Get contents of response
const response = event.Records[0].cf.response;
const headers = response.headers;
//Set new headers
headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubdomains; preload'}];
headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}];
headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}];
headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}];
headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}];
headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}];
//Return modified response
callback(null, response);
};
EOT
filename = "index.js"
}]
runtime = "nodejs16.x"
handler = "index.handler"
event_type = "origin-response"
include_body = false
}
}
# An AWS Provider configured for us-east-1 must be passed to the module, as Lambda@Edge functions must exist in us-east-1
providers = {
aws = aws.us-east-1
}
context = module.this.context
}
module "cdn" {
source = "cloudposse/cloudfront-s3-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
...
lambda_function_association = module.lambda_at_edge.lambda_function_association
}
Variables
Required Variables
Optional Variables
access_log_bucket_name
(string
) optionalDEPRECATED. Use
s3_access_log_bucket_name
instead.Default value:
null
acm_certificate_arn
(string
) optionalExisting ACM Certificate ARN
Default value:
""
additional_bucket_policy
(string
) optionalAdditional policies for the bucket. If included in the policies, the variables
${bucket_name}
,${origin_path}
and${cloudfront_origin_access_identity_iam_arn}
will be substituted.
It is also possible to override the default policy statements by providing statements withS3GetObjectForCloudFront
andS3ListBucketForCloudFront
sid.Default value:
"{ }"
aliases
(list(string)
) optionalList of FQDN's - Used to set the Alternate Domain Names (CNAMEs) setting on Cloudfront
Default value:
[ ]
allow_ssl_requests_only
(bool
) optionalSet to
true
to require requests to use Secure Socket Layer (HTTPS/SSL). This will explicitly deny access to HTTP requestsDefault value:
true
allowed_methods
(list(string)
) optionalList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFront
Default value:
[
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
]block_origin_public_access_enabled
(bool
) optionalWhen set to 'true' the s3 origin bucket will have public access block enabled
Default value:
false
bucket_versioning
(string
) optionalState of bucket versioning option
Default value:
"Disabled"
cache_policy_id
(string
) optionalThe unique identifier of the existing cache policy to attach to the default cache behavior.
If not provided, this module will add a default cache policy using other provided inputs.Default value:
null
cached_methods
(list(string)
) optionalList of cached methods (e.g. GET, PUT, POST, DELETE, HEAD)
Default value:
[
"GET",
"HEAD"
]cloudfront_access_log_bucket_name
(string
) optionalWhen
cloudfront_access_log_create_bucket
isfalse
, this is the name of the existing S3 Bucket where
Cloudfront Access Logs are to be delivered and is required. IGNORED whencloudfront_access_log_create_bucket
istrue
.Default value:
""
cloudfront_access_log_create_bucket
(bool
) optionalWhen
true
andcloudfront_access_logging_enabled
is also true, this module will create a new,
separate S3 bucket to receive Cloudfront Access Logs.Default value:
true
cloudfront_access_log_include_cookies
(bool
) optionalSet true to include cookies in Cloudfront Access Logs
Default value:
false
cloudfront_access_log_prefix
(string
) optionalPrefix to use for Cloudfront Access Log object keys. Defaults to no prefix.
Default value:
""
cloudfront_access_logging_enabled
(bool
) optionalSet true to enable delivery of Cloudfront Access Logs to an S3 bucket
Default value:
true
cloudfront_origin_access_control_id
(string
) optionalCloudFront provides two ways to send authenticated requests to an Amazon S3 origin: origin access control (OAC) and origin access identity (OAI). OAC helps you secure your origins, such as for Amazon S3.
Default value:
""
cloudfront_origin_access_identity_iam_arn
(string
) optionalExisting cloudfront origin access identity iam arn that is supplied in the s3 bucket policy
Default value:
""
cloudfront_origin_access_identity_path
(string
) optionalExisting cloudfront origin access identity path used in the cloudfront distribution's s3_origin_config content
Default value:
""
comment
(string
) optionalComment for the CloudFront distribution
Default value:
"Managed by Terraform"
compress
(bool
) optionalCompress content for web requests that include Accept-Encoding: gzip in the request header
Default value:
true
cors_allowed_headers
(list(string)
) optionalList of allowed headers for S3 bucket
Default value:
[
"*"
]cors_allowed_methods
(list(string)
) optionalList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for S3 bucket
Default value:
[
"GET"
]cors_allowed_origins
(list(string)
) optionalList of allowed origins (e.g. example.com, test.com) for S3 bucket
Default value:
[ ]
cors_expose_headers
(list(string)
) optionalList of expose header in the response for S3 bucket
Default value:
[
"ETag"
]cors_max_age_seconds
(number
) optionalTime in seconds that browser can cache the response for S3 bucket
Default value:
3600
custom_error_response
optionalList of one or more custom error response element maps
Type:
list(object({
error_caching_min_ttl = string
error_code = string
response_code = string
response_page_path = string
}))Default value:
[ ]
custom_origin_headers
(list(object({ name = string, value = string }))
) optionalA list of origin header parameters that will be sent to origin
Default value:
[ ]
custom_origins
optionalA list of additional custom website origins for this distribution.
Theorigin_access_control_id
field specifies the Origin Access Control configuration to use for this origin.
This is used to configure secure access between CloudFront and the origin.Type:
list(object({
domain_name = string
origin_id = string
origin_path = string
origin_access_control_id = optional(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
})
}))Default value:
[ ]
default_root_object
(string
) optionalObject that CloudFront return when requests the root URL
Default value:
"index.html"
default_ttl
(number
) optionalDefault amount of time (in seconds) that an object is in a CloudFront cache
Default value:
60
deployment_actions
(list(string)
) optionalList of actions to permit
deployment_principal_arns
to perform on bucket and bucket prefixes (seedeployment_principal_arns
)Default value:
[
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:DeleteObject",
"s3:ListBucket",
"s3:ListBucketMultipartUploads",
"s3:GetBucketLocation",
"s3:AbortMultipartUpload"
]deployment_principal_arns
(map(list(string))
) optional(Optional) Map of IAM Principal ARNs to lists of S3 path prefixes to grant
deployment_actions
permissions.
Resource list will include the bucket itself along with all the prefixes. Prefixes should not begin with '/'.Default value:
{ }
distribution_enabled
(bool
) optionalSet to
false
to create the distribution but still prevent CloudFront from serving requests.Default value:
true
dns_alias_enabled
(bool
) optionalCreate a DNS alias for the CDN. Requires
parent_zone_id
orparent_zone_name
Default value:
false
dns_allow_overwrite
(bool
) optionalAllow creation of DNS records in Terraform to overwrite an existing record, if any. This does not affect the ability to update the record in Terraform and does not prevent other resources within Terraform or manual Route 53 changes outside Terraform from overwriting this record. false by default. This configuration is not recommended for most environments
Default value:
false
encryption_enabled
(bool
) optionalWhen set to 'true' the resource will have aes256 encryption enabled by default
Default value:
true
error_document
(string
) optionalAn absolute path to the document to return in case of a 4XX error
Default value:
""
external_aliases
(list(string)
) optionalList of FQDN's - Used to set the Alternate Domain Names (CNAMEs) setting on Cloudfront. No new route53 records will be created for these
Default value:
[ ]
extra_logs_attributes
(list(string)
) optionalAdditional attributes to add to the end of the generated Cloudfront Access Log S3 Bucket name.
Only effective ifcloudfront_access_log_create_bucket
istrue
.Default value:
[
"logs"
]extra_origin_attributes
(list(string)
) optionalAdditional attributes to put onto the origin label
Default value:
[
"origin"
]forward_cookies
(string
) optionalSpecifies whether you want CloudFront to forward all or no cookies to the origin. Can be 'all' or 'none'
Default value:
"none"
forward_header_values
(list(string)
) optionalA list of whitelisted header values to forward to the origin (incompatible with
cache_policy_id
)Default value:
[
"Access-Control-Request-Headers",
"Access-Control-Request-Method",
"Origin"
]forward_query_string
(bool
) optionalForward query strings to the origin that is associated with this cache behavior (incompatible with
cache_policy_id
)Default value:
false
function_association
optionalA config block that triggers a CloudFront function with specific actions.
See the aws_cloudfront_distribution
documentation for more information.Type:
list(object({
event_type = string
function_arn = string
}))Default value:
[ ]
geo_restriction_locations
(list(string)
) optionalList of country codes for which CloudFront either to distribute content (whitelist) or not distribute your content (blacklist)
Default value:
[ ]
geo_restriction_type
(string
) optionalMethod that use to restrict distribution of your content by country:
none
,whitelist
, orblacklist
Default value:
"none"
http_version
(string
) optionalThe maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3 and http3
Default value:
"http2"
index_document
(string
) optionalAmazon S3 returns this index document when requests are made to the root domain or any of the subfolders
Default value:
"index.html"
ipv6_enabled
(bool
) optionalSet to true to enable an AAAA DNS record to be set as well as the A record
Default value:
true
lambda_function_association
optionalA config block that triggers a lambda@edge function with specific actions
Type:
list(object({
event_type = string
include_body = bool
lambda_arn = string
}))Default value:
[ ]
log_expiration_days
(number
) optionalNumber of days after object creation to expire Cloudfront Access Log objects.
Only effective ifcloudfront_access_log_create_bucket
istrue
.Default value:
90
log_glacier_transition_days
(number
) optionalNumber of days after object creation to move Cloudfront Access Log objects to the glacier tier.
Only effective ifcloudfront_access_log_create_bucket
istrue
.Default value:
60
log_include_cookies
(bool
) optionalDEPRECATED. Use
cloudfront_access_log_include_cookies
instead.Default value:
null
log_prefix
(string
) optionalDEPRECATED. Use
cloudfront_access_log_prefix
instead.Default value:
null
log_standard_transition_days
(number
) optionalNumber of days after object creation to move Cloudfront Access Log objects to the infrequent access tier.
Only effective ifcloudfront_access_log_create_bucket
istrue
.Default value:
30
log_versioning_enabled
(bool
) optionalSet
true
to enable object versioning in the created Cloudfront Access Log S3 Bucket.
Only effective ifcloudfront_access_log_create_bucket
istrue
.Default value:
false
logging_enabled
(bool
) optionalDEPRECATED. Use
cloudfront_access_logging_enabled
instead.Default value:
null
max_ttl
(number
) optionalMaximum amount of time (in seconds) that an object is in a CloudFront cache
Default value:
31536000
min_ttl
(number
) optionalMinimum amount of time that you want objects to stay in CloudFront caches
Default value:
0
minimum_protocol_version
(string
) optionalCloudfront TLS minimum protocol version.
Ifvar.acm_certificate_arn
is unset, only "TLSv1" can be specified. See: AWS Cloudfront create-distribution documentation
and Supported protocols and ciphers between viewers and CloudFront for more information.
Defaults to "TLSv1.2_2019" unlessvar.acm_certificate_arn
is unset, in which case it defaults toTLSv1
Default value:
""
ordered_cache
optionalAn 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.
Settarget_origin_id
to""
to specify the S3 bucket origin created by this module.Type:
list(object({
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
realtime_log_config_arn = optional(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
}))
}))Default value:
[ ]
origin_access_control_signing_behavior
(string
) optionalSpecifies which requests CloudFront signs. Specify always for the most common use case. Allowed values: always, never, and no-override.
Default value:
"always"
origin_access_type
(string
) optionalChoose to use
origin_access_control
ororgin_access_identity
Default value:
"origin_access_identity"
origin_bucket
(string
) optionalName of an existing S3 bucket to use as the origin. If this is not provided, it will create a new s3 bucket using
var.name
and other context related inputsDefault value:
null
origin_force_destroy
(bool
) optionalDelete all objects from the bucket so that the bucket can be destroyed without error (e.g.
true
orfalse
)Default value:
false
origin_groups
optionalList of Origin Groups to create in the distribution.
The values ofprimary_origin_id
andfailover_origin_id
must correspond to origin IDs existing invar.s3_origins
orvar.custom_origins
.If
primary_origin_id
is set tonull
or""
, then the origin id of the origin created by this module will be used in its place.
This is to allow for the use case of making the origin created by this module the primary origin in an origin group.Type:
list(object({
primary_origin_id = string
failover_origin_id = string
failover_criteria = list(string)
}))Default value:
[ ]
origin_path
(string
) optionalAn optional element that causes CloudFront to request your content from a directory in your Amazon S3 bucket or your custom origin. It must begin with a /. Do not add a / at the end of the path.
Default value:
""
origin_request_policy_id
(string
) optionalThe unique identifier of the origin request policy that is attached to the behavior.
Should be used in conjunction withcache_policy_id
.Default value:
null
origin_shield_enabled
(bool
) optionalIf enabled, origin shield will be enabled for the default origin
Default value:
false
origin_ssl_protocols
(list(string)
) optionalThe SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPS.
Default value:
[
"TLSv1",
"TLSv1.1",
"TLSv1.2"
]override_origin_bucket_policy
(bool
) optionalWhen using an existing origin bucket (through var.origin_bucket), setting this to 'false' will make it so the existing bucket policy will not be overriden
Default value:
true
parent_zone_id
(string
) optionalID of the hosted zone to contain this record (or specify
parent_zone_name
). Requiresdns_alias_enabled
set to trueDefault value:
null
parent_zone_name
(string
) optionalName of the hosted zone to contain this record (or specify
parent_zone_id
). Requiresdns_alias_enabled
set to trueDefault value:
""
price_class
(string
) optionalPrice class for this distribution:
PriceClass_All
,PriceClass_200
,PriceClass_100
Default value:
"PriceClass_100"
query_string_cache_keys
(list(string)
) optionalWhen
forward_query_string
is enabled, only the query string keys listed in this argument are cached (incompatible withcache_policy_id
)Default value:
[ ]
realtime_log_config_arn
(string
) optionalThe ARN of the real-time log configuration that is attached to this cache behavior
Default value:
null
redirect_all_requests_to
(string
) optionalA hostname to redirect all website requests for this distribution to. If this is set, it overrides other website settings
Default value:
""
response_headers_policy_id
(string
) optionalThe identifier for a response headers policy
Default value:
""
routing_rules
(string
) optionalA json array containing routing rules describing redirect behavior and when redirects are applied
Default value:
""
s3_access_log_bucket_name
(string
) optionalName of the existing S3 bucket where S3 Access Logs will be delivered. Default is not to enable S3 Access Logging.
Default value:
""
s3_access_log_prefix
(string
) optionalPrefix to use for S3 Access Log object keys. Defaults to
logs/${module.this.id}
Default value:
""
s3_access_logging_enabled
(bool
) optionalSet
true
to deliver S3 Access Logs to thes3_access_log_bucket_name
bucket.
Defaults tofalse
ifs3_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.Default value:
null
s3_object_ownership
(string
) optionalSpecifies the S3 object ownership control on the origin bucket. Valid values are
ObjectWriter
,BucketOwnerPreferred
, and 'BucketOwnerEnforced'.Default value:
"ObjectWriter"
s3_origins
optionalA list of S3 origins (in addition to the one created by this module) for this distribution.
S3 buckets configured as websites arecustom_origins
, nots3_origins
.
Specifyings3_origin_config.origin_access_identity
asnull
or""
will have it translated to theorigin_access_identity
used by the origin created by the module.Type:
list(object({
domain_name = string
origin_id = string
origin_path = string
origin_access_control_id = string
s3_origin_config = object({
origin_access_identity = string
})
}))Default value:
[ ]
s3_website_password_enabled
(bool
) optionalIf set to true, and
website_enabled
is also true, a password will be required in theReferrer
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.Default value:
false
trusted_key_groups
(list(string)
) optionalA list of key group IDs that CloudFront can use to validate signed URLs or signed cookies.
Default value:
[ ]
trusted_signers
(list(string)
) optionalThe AWS accounts, if any, that you want to allow to create signed URLs for private content. 'self' is acceptable.
Default value:
[ ]
versioning_enabled
(bool
) optionalWhen set to 'true' the s3 origin bucket will have versioning enabled
Default value:
true
viewer_protocol_policy
(string
) optionalLimit the protocol users can use to access content. One of
allow-all
,https-only
, orredirect-to-https
Default value:
"redirect-to-https"
wait_for_deployment
(bool
) optionalWhen set to 'true' the resource will wait for the distribution status to change from InProgress to Deployed
Default value:
true
web_acl_id
(string
) optionalID of the AWS WAF web ACL that is associated with the distribution
Default value:
""
website_enabled
(bool
) optionalSet to true to enable the created S3 bucket to serve as a website independently of Cloudfront,
and to use that website as the origin. See the README for details and caveats. See alsos3_website_password_enabled
.Default value:
false
Context Variables
The following variables are defined in the context.tf
file of this module and part of the terraform-null-label pattern.
context.tf
file of this module and part of the terraform-null-label pattern.additional_tag_map
(map(string)
) optionalAdditional key-value pairs to add to each map in
tags_as_list_of_maps
. Not added totags
orid
.
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.Required: No
Default value:
{ }
attributes
(list(string)
) optionalID element. Additional attributes (e.g.
workers
orcluster
) to add toid
,
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 thedelimiter
and treated as a single ID element.Required: No
Default value:
[ ]
context
(any
) optionalSingle object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables asnull
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.Required: No
Default value:
{
"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": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}delimiter
(string
) optionalDelimiter to be used between ID elements.
Defaults to-
(hyphen). Set to""
to use no delimiter at all.Required: No
Default value:
null
descriptor_formats
(any
) optionalDescribe 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 isany
so the map values can later be enhanced to provide additional options.)
format
is a Terraform format string to be passed to theformat()
function.
labels
is a list of labels, in order, to pass toformat()
function.
Label values will be normalized before being passed toformat()
so they will be
identical to how they appear inid
.
Default is{}
(descriptors
output will be empty).Required: No
Default value:
{ }
enabled
(bool
) optionalSet to false to prevent the module from creating any resources
Required: NoDefault value:
null
environment
(string
) optionalID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: NoDefault value:
null
id_length_limit
(number
) optionalLimit
id
to this many characters (minimum 6).
Set to0
for unlimited length.
Set tonull
for keep the existing setting, which defaults to0
.
Does not affectid_full
.Required: No
Default value:
null
label_key_case
(string
) optionalControls the letter case of the
tags
keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via thetags
input.
Possible values:lower
,title
,upper
.
Default value:title
.Required: No
Default value:
null
label_order
(list(string)
) optionalThe 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.Required: No
Default value:
null
label_value_case
(string
) optionalControls 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 thetags
input.
Possible values:lower
,title
,upper
andnone
(no transformation).
Set this totitle
and setdelimiter
to""
to yield Pascal Case IDs.
Default value:lower
.Required: No
Default value:
null
labels_as_tags
(set(string)
) optionalSet 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 thetags
output.
Set to[]
to suppress all generated tags.
Notes:
The value of thename
tag, if included, will be theid
, not thename
.
Unlike othernull-label
inputs, the initial setting oflabels_as_tags
cannot be
changed in later chained modules. Attempts to change it will be silently ignored.Required: No
Default value:
[
"default"
]name
(string
) optionalID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as atag
.
The "name" tag is set to the fullid
string. There is no tag with the value of thename
input.Required: No
Default value:
null
namespace
(string
) optionalID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: NoDefault value:
null
regex_replace_chars
(string
) optionalTerraform 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.Required: No
Default value:
null
stage
(string
) optionalID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: NoDefault value:
null
tags
(map(string)
) optionalAdditional tags (e.g.
{'BusinessUnit': 'XYZ'}
).
Neither the tag keys nor the tag values will be modified by this module.Required: No
Default value:
{ }
tenant
(string
) optionalID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: NoDefault value:
null
Outputs
aliases
Aliases of the CloudFront distribution.
cf_access_control_id
CloudFront Origin Access Control ID
cf_arn
ARN of AWS CloudFront distribution
cf_domain_name
Domain name corresponding to the distribution
cf_etag
Current version of the distribution's information
cf_hosted_zone_id
CloudFront Route 53 zone ID
cf_id
ID of AWS CloudFront distribution
cf_identity_iam_arn
CloudFront Origin Access Identity IAM ARN
cf_origin_groups
List of Origin Groups in the CloudFront distribution.
cf_origin_ids
List of Origin IDs in the CloudFront distribution.
cf_primary_origin_id
The ID of the origin created by this module.
cf_s3_canonical_user_id
Canonical user ID for CloudFront Origin Access Identity
cf_status
Current status of the distribution
logs
Log bucket resource
s3_bucket
Name of origin S3 bucket
s3_bucket_arn
ARN of origin S3 bucket
s3_bucket_domain_name
Domain of origin S3 bucket
s3_bucket_policy
Final computed S3 bucket policy
Dependencies
Requirements
terraform
, version:>= 1.3
aws
, version:>= 4.9
random
, version:>= 2.2
time
, version:>= 0.7
Providers
aws
, version:>= 4.9
random
, version:>= 2.2
time
, version:>= 0.7
Modules
Name | Version | Source | Description |
---|---|---|---|
dns | 0.13.0 | cloudposse/route53-alias/aws | n/a |
logs | 1.4.2 | cloudposse/s3-log-storage/aws | n/a |
origin_label | 0.25.0 | cloudposse/label/null | n/a |
this | 0.25.0 | cloudposse/label/null | n/a |
Resources
The following resources are used by this module:
aws_cloudfront_distribution.default
(resource)aws_cloudfront_origin_access_control.default
(resource)aws_cloudfront_origin_access_identity.default
(resource)aws_s3_bucket.origin
(resource)aws_s3_bucket_acl.origin
(resource)aws_s3_bucket_cors_configuration.origin
(resource)aws_s3_bucket_ownership_controls.origin
(resource)aws_s3_bucket_policy.default
(resource)aws_s3_bucket_public_access_block.origin
(resource)aws_s3_bucket_server_side_encryption_configuration.origin
(resource)aws_s3_bucket_versioning.origin
(resource)random_password.referer
(resource)time_sleep.wait_for_aws_s3_bucket_settings
(resource)
Data Sources
The following data sources are used by this module:
aws_caller_identity.current
(data source)aws_iam_policy_document.combined
(data source)aws_iam_policy_document.deployment
(data source)aws_iam_policy_document.s3_origin_access_control
(data source)aws_iam_policy_document.s3_origin_access_identity
(data source)aws_iam_policy_document.s3_ssl_only
(data source)aws_iam_policy_document.s3_website_origin
(data source)aws_partition.current
(data source)aws_region.current
(data source)aws_s3_bucket.cf_logs
(data source)aws_s3_bucket.origin
(data source)