Module: cloudfront-cdn
Terraform Module that implements a CloudFront Distribution (CDN) for a custom origin (e.g. website) and ships logs to a bucket.
If you need to accelerate an S3 bucket, we suggest using terraform-aws-cloudfront-s3-cdn
instead.
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.
module "cdn" {
source = "cloudposse/cloudfront-cdn/aws"
# Cloud Posse recommends pinning every module to a specific version
# version = "x.x.x"
namespace = "eg"
stage = "prod"
name = "app"
aliases = ["www.example.net"]
origin_domain_name = "origin.example.com"
parent_zone_name = "example.net"
}
Complete example of setting up CloudFront Distribution with Cache Behaviors for a WordPress site: examples/wordpress
Generating ACM Certificate
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
Variables
Required Variables
Optional Variables
acm_certificate_arn
(string
) optionalExisting ACM Certificate ARN
Default value:
""
aliases
(list(string)
) optionalList of aliases. CAUTION! Names MUSTN'T contain trailing
.
Default value:
[ ]
allowed_methods
(list(string)
) optionalList of allowed methods (e.g.
GET, PUT, POST, DELETE, HEAD
) for AWS CloudFrontDefault value:
[
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
]cache_policy_id
(string
) optionalID of the cache policy attached to the cache behavior
Default value:
null
cached_methods
(list(string)
) optionalList of cached methods (e.g.
GET, PUT, POST, DELETE, HEAD
)Default value:
[
"GET",
"HEAD"
]comment
(string
) optionalComment for the origin access identity
Default value:
"Managed by Terraform"
compress
(bool
) optionalWhether you want CloudFront to automatically compress content for web requests that include Accept-Encoding: gzip in the request header (default: false)
Default value:
false
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_header
optionalList of one or more custom headers passed to the origin
Type:
list(object({
name = string
value = string
}))Default value:
[ ]
custom_origins
optionalOne or more custom origins for this distribution (multiples allowed). See documentation for configuration options description https://www.terraform.io/docs/providers/aws/r/cloudfront_distribution.html#origin-arguments
Type:
list(object({
domain_name = string
origin_id = string
origin_path = string
origin_access_control_id = 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
})
s3_origin_config = object({
origin_access_identity = string
})
}))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
distribution_enabled
(bool
) optionalSet to
true
if you want CloudFront to begin processing requests as soon as the distribution is created, or to false if you do not want CloudFront to begin processing requests after the distribution is created.Default value:
true
dns_aliases_enabled
(bool
) optionalSet to false to prevent dns records for aliases from being created
Default value:
true
forward_cookies
(string
) optionalSpecifies whether you want CloudFront to forward cookies to the origin. Valid options are all, none or whitelist
Default value:
"none"
forward_cookies_whitelisted_names
(list(string)
) optionalList of forwarded cookie names
Default value:
[ ]
forward_headers
(list(string)
) optionalSpecifies the Headers, if any, that you want CloudFront to vary upon for this cache behavior. Specify
*
to include all headers.Default value:
[ ]
forward_query_string
(bool
) optionalForward query strings to the origin that is associated with this cache behavior
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"
is_ipv6_enabled
(bool
) optionalState of CloudFront IPv6
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_bucket_fqdn
(string
) optionalOptional fqdn of logging bucket, if not supplied a bucket will be generated.
Default value:
""
log_expiration_days
(number
) optionalNumber of days after which to expunge the objects
Default value:
90
log_force_destroy
(bool
) optionalApplies to log bucket created by this module only. If true, all objects will be deleted from the bucket on destroy, so that the bucket can be destroyed without error. These objects are not recoverable.
Default value:
false
log_glacier_transition_days
(number
) optionalNumber of days after which to move the data to the glacier storage tier
Default value:
60
log_include_cookies
(bool
) optionalInclude cookies in access logs
Default value:
false
log_prefix
(string
) optionalPath of logs in S3 bucket
Default value:
""
log_standard_transition_days
(number
) optionalNumber of days to persist in the standard storage tier before moving to the glacier tier
Default value:
30
logging_enabled
(bool
) optionalWhen true, access logs will be sent to a newly created s3 bucket
Default value:
true
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
ordered_cache
optionalAn ordered list of cache behaviors resource for this distribution. List from top to bottom in order of precedence. The topmost cache behavior will have precedence 0.
The fields can be described by the other variables in this file. For example, the field 'lambda_function_association' in this object has
a description in var.lambda_function_association variable earlier in this file. The only difference is that fields on this object are in ordered caches, whereas the rest
of the vars in this file apply only to the default cache. Put value""
on fieldtarget_origin_id
to specify default s3 bucket origin.Type:
list(object({
target_origin_id = string
path_pattern = string
allowed_methods = list(string)
cached_methods = list(string)
cache_policy_id = string
origin_request_policy_id = string
compress = bool
viewer_protocol_policy = string
min_ttl = number
default_ttl = number
max_ttl = number
forward_query_string = bool
forward_header_values = list(string)
forward_cookies = string
response_headers_policy_id = 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_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:
null
origin_access_identity_enabled
(bool
) optionalWhen true, creates origin access identity resource
Default value:
true
origin_domain_name
(string
) optionalThe DNS domain name of your custom origin (e.g. website)
Default value:
""
origin_http_port
(number
) optionalThe HTTP port the custom origin listens on
Default value:
"80"
origin_https_port
(number
) optionalThe HTTPS port the custom origin listens on
Default value:
443
origin_keepalive_timeout
(number
) optionalThe Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.
Default value:
60
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_protocol_policy
(string
) optionalThe origin protocol policy to apply to your origin. One of http-only, https-only, or match-viewer
Default value:
"match-viewer"
origin_read_timeout
(number
) optionalThe Custom Read timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.
Default value:
60
origin_request_policy_id
(string
) optionalID of the origin request policy attached to the cache behavior
Default value:
null
origin_shield
optionalThe CloudFront Origin Shield settings
Type:
object({
enabled = bool
region = string
})Default value:
null
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"
]parent_zone_id
(string
) optionalID of the hosted zone to contain this record (or specify
parent_zone_name
)Default value:
""
parent_zone_name
(string
) optionalName of the hosted zone to contain this record (or specify
parent_zone_id
)Default value:
""
price_class
(string
) optionalPrice class for this distribution:
PriceClass_All
,PriceClass_200
,PriceClass_100
Default value:
"PriceClass_100"
realtime_log_config_arn
(string
) optionalThe ARN of the real-time log configuration that is attached to this cache behavior
Default value:
null
response_headers_policy_id
(string
) optionalThe identifier for a response headers policy
Default value:
""
trusted_signers
(list(string)
) optionalList of AWS account IDs (or self) that you want to allow to create signed URLs for private content
Default value:
[ ]
viewer_minimum_protocol_version
(string
) optionalThe minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. This is ignored if the default CloudFront certificate is used.
Default value:
"TLSv1.2_2021"
viewer_protocol_policy
(string
) optionalallow-all, redirect-to-https
Default value:
"redirect-to-https"
web_acl_id
(string
) optionalID of the AWS WAF web ACL that is associated with the distribution
Default value:
""
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
cf_aliases
Extra CNAMEs of AWS CloudFront
cf_arn
ARN of 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 CloudFront distribution
cf_origin_access_identity
A shortcut to the full path for the origin access identity to use in CloudFront
cf_status
Current status of the distribution
logs
Logs resource
Dependencies
Requirements
terraform
, version:>= 1.0
aws
, version:>= 4.9.0
local
, version:>= 1.2
Providers
aws
, version:>= 4.9.0
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_identity.default
(resource)
Data Sources
The following data sources are used by this module: