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

Variables

Required Variables

Optional Variables

acm_certificate_arn (string) optional

Existing ACM Certificate ARN


Default value: ""

aliases (list(string)) optional

List of aliases. CAUTION! Names MUSTN'T contain trailing .


Default value: [ ]

allowed_methods (list(string)) optional

List of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFront


Default value:

[
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
]
cache_policy_id (string) optional

ID of the cache policy attached to the cache behavior


Default value: null

cached_methods (list(string)) optional

List of cached methods (e.g. GET, PUT, POST, DELETE, HEAD)


Default value:

[
"GET",
"HEAD"
]
comment (string) optional

Comment for the origin access identity


Default value: "Managed by Terraform"

compress (bool) optional

Whether 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 optional

List 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 optional

List of one or more custom headers passed to the origin


Type:

list(object({
name = string
value = string
}))

Default value: [ ]

custom_origins optional

One 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) optional

Object that CloudFront return when requests the root URL


Default value: "index.html"

default_ttl (number) optional

Default amount of time (in seconds) that an object is in a CloudFront cache


Default value: 60

distribution_enabled (bool) optional

Set 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) optional

Set to false to prevent dns records for aliases from being created


Default value: true

forward_cookies (string) optional

Specifies 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)) optional

List of forwarded cookie names


Default value: [ ]

forward_headers (list(string)) optional

Specifies 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) optional

Forward query strings to the origin that is associated with this cache behavior


Default value: false

function_association optional

A 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)) optional

List of country codes for which CloudFront either to distribute content (whitelist) or not distribute your content (blacklist)


Default value: [ ]

geo_restriction_type (string) optional

Method that use to restrict distribution of your content by country: none, whitelist, or blacklist


Default value: "none"

http_version (string) optional

The maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3 and http3.


Default value: "http2"

is_ipv6_enabled (bool) optional

State of CloudFront IPv6


Default value: true

lambda_function_association optional

A 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) optional

Optional fqdn of logging bucket, if not supplied a bucket will be generated.


Default value: ""

log_expiration_days (number) optional

Number of days after which to expunge the objects


Default value: 90

log_force_destroy (bool) optional

Applies 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) optional

Number of days after which to move the data to the glacier storage tier


Default value: 60

log_include_cookies (bool) optional

Include cookies in access logs


Default value: false

log_prefix (string) optional

Path of logs in S3 bucket


Default value: ""

log_standard_transition_days (number) optional

Number of days to persist in the standard storage tier before moving to the glacier tier


Default value: 30

logging_enabled (bool) optional

When true, access logs will be sent to a newly created s3 bucket


Default value: true

max_ttl (number) optional

Maximum amount of time (in seconds) that an object is in a CloudFront cache


Default value: 31536000

min_ttl (number) optional

Minimum amount of time that you want objects to stay in CloudFront caches


Default value: 0

ordered_cache optional

An 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.



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) optional

CloudFront 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) optional

When true, creates origin access identity resource


Default value: true

origin_domain_name (string) optional

The DNS domain name of your custom origin (e.g. website)


Default value: ""

origin_http_port (number) optional

The HTTP port the custom origin listens on


Default value: "80"

origin_https_port (number) optional

The HTTPS port the custom origin listens on


Default value: 443

origin_keepalive_timeout (number) optional

The 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) optional

An 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) optional

The 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) optional

The 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) optional

ID of the origin request policy attached to the cache behavior


Default value: null

origin_shield optional

The CloudFront Origin Shield settings


Type:

object({
enabled = bool
region = string
})

Default value: null

origin_ssl_protocols (list(string)) optional

The 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) optional

ID of the hosted zone to contain this record (or specify parent_zone_name)


Default value: ""

parent_zone_name (string) optional

Name of the hosted zone to contain this record (or specify parent_zone_id)


Default value: ""

price_class (string) optional

Price class for this distribution: PriceClass_All, PriceClass_200, PriceClass_100


Default value: "PriceClass_100"

realtime_log_config_arn (string) optional

The ARN of the real-time log configuration that is attached to this cache behavior


Default value: null

response_headers_policy_id (string) optional

The identifier for a response headers policy


Default value: ""

trusted_signers (list(string)) optional

List 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) optional

The 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) optional

allow-all, redirect-to-https


Default value: "redirect-to-https"

web_acl_id (string) optional

ID 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.

additional_tag_map (map(string)) optional

Additional 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.


Required: No

Default value: { }

attributes (list(string)) optional

ID 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.


Required: No

Default value: [ ]

context (any) optional

Single 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.


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) optional

Delimiter 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) optional

Describe 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).


Required: No

Default value: { }

enabled (bool) optional

Set to false to prevent the module from creating any resources
Required: No

Default value: null

environment (string) optional

ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'
Required: No

Default value: null

id_length_limit (number) optional

Limit 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.


Required: No

Default value: null

label_key_case (string) optional

Controls 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.


Required: No

Default value: null

label_order (list(string)) optional

The 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) optional

Controls 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.


Required: No

Default value: null

labels_as_tags (set(string)) optional

Set 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.


Required: No

Default value:

[
"default"
]
name (string) optional

ID 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.


Required: No

Default value: null

namespace (string) optional

ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique
Required: No

Default value: null

regex_replace_chars (string) optional

Terraform 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) optional

ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'
Required: No

Default value: null

tags (map(string)) optional

Additional 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) optional

ID element (Rarely used, not included by default). A customer identifier, indicating who this instance of a resource is for
Required: No

Default 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

NameVersionSourceDescription
dns0.13.0cloudposse/route53-alias/awsn/a
logs1.4.2cloudposse/s3-log-storage/awsn/a
origin_label0.25.0cloudposse/label/nulln/a
this0.25.0cloudposse/label/nulln/a

Resources

The following resources are used by this module:

Data Sources

The following data sources are used by this module: