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:
nullcached_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:
falsecustom_error_responseoptionalList of one or more custom error response element maps
Type:
list(object({
error_caching_min_ttl = optional(string, null)
error_code = string
response_code = optional(string, null)
response_page_path = optional(string, null)
}))Default value:
[ ]custom_headeroptionalList of one or more custom headers passed to the origin
Type:
list(object({
name = string
value = string
}))Default value:
[ ]custom_originsoptionalOne 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 = optional(string, "")
origin_access_control_id = optional(string, null)
custom_headers = optional(list(object({
name = string
value = string
})), [])
custom_origin_config = optional(object({
http_port = optional(number, 80)
https_port = optional(number, 443)
origin_protocol_policy = optional(string, "match-viewer")
origin_ssl_protocols = optional(list(string), ["TLSv1", "TLSv1.1", "TLSv1.2"])
origin_keepalive_timeout = optional(number, 5)
origin_read_timeout = optional(number, 30)
}), null)
s3_origin_config = optional(object({
origin_access_identity = string
}), null)
origin_shield = optional(object({
enabled = optional(bool, false)
region = optional(string, null)
}), null)
}))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:
60distribution_enabled(bool) optionalSet to
trueif 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:
truedns_aliases_enabled(bool) optionalSet to false to prevent dns records for aliases from being created
Default value:
trueforward_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:
falsefunction_associationoptionalA 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, orblacklistDefault value:
"none"grpc_configoptionalThe gRPC configuration for the default CloudFront distribution cache behavior
Type:
object({
enabled = bool
})Default value:
{
"enabled": false
}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:
truelambda_function_associationoptionalA config block that triggers a Lambda@Edge function with specific actions
Type:
list(object({
event_type = string
include_body = optional(bool, false)
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:
90log_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:
falselog_glacier_transition_days(number) optionalNumber of days after which to move the data to the glacier storage tier
Default value:
60log_include_cookies(bool) optionalInclude cookies in access logs
Default value:
falselog_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:
30logging_enabled(bool) optionalWhen true, access logs will be sent to a newly created s3 bucket
Default value:
truemax_ttl(number) optionalMaximum amount of time (in seconds) that an object is in a CloudFront cache
Default value:
31536000min_ttl(number) optionalMinimum amount of time that you want objects to stay in CloudFront caches
Default value:
0ordered_cacheoptionalAn 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_idto specify default s3 bucket origin.Type:
list(object({
target_origin_id = string
path_pattern = string
allowed_methods = optional(list(string), ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"])
cached_methods = optional(list(string), ["GET", "HEAD"])
cache_policy_id = optional(string, null)
origin_request_policy_id = optional(string, null)
compress = optional(bool, false)
viewer_protocol_policy = optional(string, "redirect-to-https")
min_ttl = optional(number, 0)
default_ttl = optional(number, 60)
max_ttl = optional(number, 31536000)
forward_query_string = optional(bool, false)
forward_header_values = optional(list(string), [])
forward_cookies = optional(string, "none")
forward_cookies_whitelisted_names = optional(list(string), [])
response_headers_policy_id = optional(string, "")
grpc_config = optional(object({
enabled = bool
}), { enabled = false })
lambda_function_association = optional(list(object({
event_type = string
include_body = optional(bool, false)
lambda_arn = string
})), [])
function_association = optional(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:
nullorigin_access_identity_enabled(bool) optionalWhen true, creates origin access identity resource
Default value:
trueorigin_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:
443origin_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:
5origin_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:
30origin_request_policy_id(string) optionalID of the origin request policy attached to the cache behavior
Default value:
nullorigin_shieldoptionalThe CloudFront Origin Shield settings
Type:
object({
enabled = optional(bool, false)
region = optional(string, null)
})Default value:
nullorigin_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"
]origin_type(string) optionalThe type of origin configuration to use. Valid values are 'custom' or 's3'.
Default value:
"custom"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_100Default 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:
nullresponse_headers_policy_id(string) optionalThe identifier for a response headers policy
Default value:
""s3_origin_configoptionalOptional configuration for an S3 origin.
Type:
object({
origin_access_identity = string
})Default value:
nulltrusted_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 totagsorid.
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.
workersorcluster) 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 asnullto 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:
nulldescriptor_formats(any) optionalDescribe additional descriptors to be output in the
descriptorsoutput map.
Map of maps. Keys are names of descriptors. Values are maps of the form
\{<br/> format = string<br/> labels = list(string)<br/> \}
(Type isanyso the map values can later be enhanced to provide additional options.)
formatis a Terraform format string to be passed to theformat()function.
labelsis 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{}(descriptorsoutput will be empty).Required: No
Default value:
{ }enabled(bool) optionalSet to false to prevent the module from creating any resources
Required: NoDefault value:
nullenvironment(string) optionalID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: NoDefault value:
nullid_length_limit(number) optionalLimit
idto this many characters (minimum 6).
Set to0for unlimited length.
Set tonullfor keep the existing setting, which defaults to0.
Does not affectid_full.Required: No
Default value:
nulllabel_key_case(string) optionalControls the letter case of the
tagskeys (label names) for tags generated by this module.
Does not affect keys of tags passed in via thetagsinput.
Possible values:lower,title,upper.
Default value:title.Required: No
Default value:
nulllabel_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:
nulllabel_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 thetagsinput.
Possible values:lower,title,upperandnone(no transformation).
Set this totitleand setdelimiterto""to yield Pascal Case IDs.
Default value:lower.Required: No
Default value:
nulllabels_as_tags(set(string)) optionalSet of labels (ID elements) to include as tags in the
tagsoutput.
Default is to include all labels.
Tags with empty values will not be included in thetagsoutput.
Set to[]to suppress all generated tags.
Notes:
The value of thenametag, if included, will be theid, not thename.
Unlike othernull-labelinputs, the initial setting oflabels_as_tagscannot 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 fullidstring. There is no tag with the value of thenameinput.Required: No
Default value:
nullnamespace(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:
nullregex_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:
nullstage(string) optionalID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: NoDefault value:
nulltags(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_aliasesExtra CNAMEs of AWS CloudFront
cf_arnARN of CloudFront distribution
cf_domain_nameDomain name corresponding to the distribution
cf_etagCurrent version of the distribution's information
cf_hosted_zone_idCloudFront Route 53 Zone ID
cf_idID of CloudFront distribution
cf_origin_access_identityA shortcut to the full path for the origin access identity to use in CloudFront
cf_statusCurrent status of the distribution
logsLogs resource
Dependencies
Requirements
terraform, version:>= 1.0aws, version:>= 4.9.0local, 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.4 | 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: