Skip to main content

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

Requirements

NameVersion
terraform>= 1.0
aws>= 4.9.0
local>= 1.2

Providers

NameVersion
aws>= 4.9.0

Modules

NameSourceVersion
dnscloudposse/route53-alias/aws0.13.0
logscloudposse/s3-log-storage/aws1.4.2
origin_labelcloudposse/label/null0.25.0
thiscloudposse/label/null0.25.0

Resources

NameType
aws_cloudfront_distribution.defaultresource
aws_cloudfront_origin_access_identity.defaultresource

Inputs

NameDescriptionTypeDefaultRequired
acm_certificate_arnExisting ACM Certificate ARNstring""no
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.
map(string){}no
aliasesList of aliases. CAUTION! Names MUSTN'T contain trailing .list(string)[]no
allowed_methodsList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFrontlist(string)
[
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
]
no
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.
list(string)[]no
cache_policy_idID of the cache policy attached to the cache behaviorstringnullno
cached_methodsList of cached methods (e.g. GET, PUT, POST, DELETE, HEAD)list(string)
[
"GET",
"HEAD"
]
no
commentComment for the origin access identitystring"Managed by Terraform"no
compressWhether you want CloudFront to automatically compress content for web requests that include Accept-Encoding: gzip in the request header (default: false)boolfalseno
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.
any
{
"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
}
no
custom_error_responseList of one or more custom error response element maps
list(object({
error_caching_min_ttl = string
error_code = string
response_code = string
response_page_path = string
}))
[]no
custom_headerList of one or more custom headers passed to the origin
list(object({
name = string
value = string
}))
[]no
custom_originsOne 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
list(object({
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
})
s3_origin_config = object({
origin_access_identity = string
})
}))
[]no
default_root_objectObject that CloudFront return when requests the root URLstring"index.html"no
default_ttlDefault amount of time (in seconds) that an object is in a CloudFront cachenumber60no
delimiterDelimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
stringnullno
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).
any{}no
distribution_enabledSet 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.booltrueno
dns_aliases_enabledSet to false to prevent dns records for aliases from being createdbooltrueno
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
forward_cookiesSpecifies whether you want CloudFront to forward cookies to the origin. Valid options are all, none or whiteliststring"none"no
forward_cookies_whitelisted_namesList of forwarded cookie nameslist(string)[]no
forward_headersSpecifies the Headers, if any, that you want CloudFront to vary upon for this cache behavior. Specify * to include all headers.list(string)[]no
forward_query_stringForward query strings to the origin that is associated with this cache behaviorboolfalseno
function_associationA config block that triggers a CloudFront function with specific actions.
See the aws_cloudfront_distribution
documentation for more information.
list(object({
event_type = string
function_arn = string
}))
[]no
geo_restriction_locationsList of country codes for which CloudFront either to distribute content (whitelist) or not distribute your content (blacklist)list(string)[]no
geo_restriction_typeMethod that use to restrict distribution of your content by country: none, whitelist, or blackliststring"none"no
http_versionThe maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3 and http3.string"http2"no
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.
numbernullno
is_ipv6_enabledState of CloudFront IPv6booltrueno
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.
stringnullno
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.
list(string)nullno
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.
stringnullno
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.
Notes:
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.
set(string)
[
"default"
]
no
lambda_function_associationA config block that triggers a Lambda@Edge function with specific actions
list(object({
event_type = string
include_body = bool
lambda_arn = string
}))
[]no
log_bucket_fqdnOptional fqdn of logging bucket, if not supplied a bucket will be generated.string""no
log_expiration_daysNumber of days after which to expunge the objectsnumber90no
log_force_destroyApplies 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.boolfalseno
log_glacier_transition_daysNumber of days after which to move the data to the glacier storage tiernumber60no
log_include_cookiesInclude cookies in access logsboolfalseno
log_prefixPath of logs in S3 bucketstring""no
log_standard_transition_daysNumber of days to persist in the standard storage tier before moving to the glacier tiernumber30no
logging_enabledWhen true, access logs will be sent to a newly created s3 bucketbooltrueno
max_ttlMaximum amount of time (in seconds) that an object is in a CloudFront cachenumber31536000no
min_ttlMinimum amount of time that you want objects to stay in CloudFront cachesnumber0no
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.
stringnullno
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 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 field target_origin_id to specify default s3 bucket origin.
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
}))
}))
[]no
origin_access_identity_enabledWhen true, creates origin access identity resourcebooltrueno
origin_domain_nameThe DNS domain name of your custom origin (e.g. website)string""no
origin_http_portThe HTTP port the custom origin listens onnumber"80"no
origin_https_portThe HTTPS port the custom origin listens onnumber443no
origin_keepalive_timeoutThe Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.number60no
origin_pathAn 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.string""no
origin_protocol_policyThe origin protocol policy to apply to your origin. One of http-only, https-only, or match-viewerstring"match-viewer"no
origin_read_timeoutThe Custom Read timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase.number60no
origin_request_policy_idID of the origin request policy attached to the cache behaviorstringnullno
origin_shieldThe CloudFront Origin Shield settings
object({
enabled = bool
region = string
})
nullno
origin_ssl_protocolsThe SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPSlist(string)
[
"TLSv1",
"TLSv1.1",
"TLSv1.2"
]
no
parent_zone_idID of the hosted zone to contain this record (or specify parent_zone_name)string""no
parent_zone_nameName of the hosted zone to contain this record (or specify parent_zone_id)string""no
price_classPrice class for this distribution: PriceClass_All, PriceClass_200, PriceClass_100string"PriceClass_100"no
realtime_log_config_arnThe ARN of the real-time log configuration that is attached to this cache behaviorstringnullno
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.
stringnullno
response_headers_policy_idThe identifier for a response headers policystring""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.
map(string){}no
tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
trusted_signersList of AWS account IDs (or self) that you want to allow to create signed URLs for private contentlist(string)[]no
viewer_minimum_protocol_versionThe 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.string"TLSv1.2_2021"no
viewer_protocol_policyallow-all, redirect-to-httpsstring"redirect-to-https"no
web_acl_idID of the AWS WAF web ACL that is associated with the distributionstring""no

Outputs

NameDescription
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