Home

Awesome

<!-- markdownlint-disable -->

<a href="https://cpco.io/homepage"><img src="https://github.com/cloudposse/terraform-aws-cloudfront-s3-cdn/blob/main/.github/banner.png?raw=true" alt="Project Banner"/></a><br/> <p align="right"> <a href="https://github.com/cloudposse/terraform-aws-cloudfront-s3-cdn/releases/latest"><img src="https://img.shields.io/github/release/cloudposse/terraform-aws-cloudfront-s3-cdn.svg?style=for-the-badge" alt="Latest Release"/></a><a href="https://github.com/cloudposse/terraform-aws-cloudfront-s3-cdn/commits"><img src="https://img.shields.io/github/last-commit/cloudposse/terraform-aws-cloudfront-s3-cdn.svg?style=for-the-badge" alt="Last Updated"/></a><a href="https://slack.cloudposse.com"><img src="https://slack.cloudposse.com/for-the-badge.svg" alt="Slack Community"/></a></p>

<!-- markdownlint-restore --> <!-- ** DO NOT EDIT THIS FILE ** ** This file was automatically generated by the `cloudposse/build-harness`. ** 1) Make all changes to `README.yaml` ** 2) Run `make init` (you only need to do this once) ** 3) Run`make readme` to rebuild this file. ** ** (We maintain HUNDREDS of open source projects. This is how we maintain our sanity.) ** -->

Terraform module to provision an AWS CloudFront CDN with an S3 origin.

[!TIP]

πŸ‘½ Use Atmos with Terraform

Cloud Posse uses atmos to easily orchestrate multiple environments using Terraform. <br/> Works with Github Actions, Atlantis, or Spacelift.

<details> <summary><strong>Watch demo of using Atmos with Terraform</strong></summary> <img src="https://github.com/cloudposse/atmos/blob/master/docs/demo.gif?raw=true"/><br/> <i>Example of running <a href="https://atmos.tools"><code>atmos</code></a> to manage infrastructure from our <a href="https://atmos.tools/quick-start/">Quick Start</a> tutorial.</i> </detalis>

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:

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:

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

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

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cnames-and-https-requirements.html

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
}

[!IMPORTANT] In Cloud Posse's examples, we avoid pinning modules to specific versions to prevent discrepancies between the documentation and the latest released versions. However, for your own projects, we strongly advise pinning each module to the exact version you're using. This practice ensures the stability of your infrastructure. Additionally, we recommend implementing a systematic approach for updating versions to avoid unexpected changes.

<!-- markdownlint-disable -->

Makefile Targets

Available targets:

  help                                Help screen
  help/all                            Display help for all targets
  help/short                          This help short screen
  lint                                Lint terraform code

<!-- markdownlint-restore --> <!-- markdownlint-disable -->

Requirements

NameVersion
<a name="requirement_terraform"></a> terraform>= 1.3
<a name="requirement_aws"></a> aws>= 4.9
<a name="requirement_random"></a> random>= 2.2
<a name="requirement_time"></a> time>= 0.7

Providers

NameVersion
<a name="provider_aws"></a> aws>= 4.9
<a name="provider_random"></a> random>= 2.2
<a name="provider_time"></a> time>= 0.7

Modules

NameSourceVersion
<a name="module_dns"></a> dnscloudposse/route53-alias/aws0.13.0
<a name="module_logs"></a> logscloudposse/s3-log-storage/aws1.4.2
<a name="module_origin_label"></a> origin_labelcloudposse/label/null0.25.0
<a name="module_this"></a> thiscloudposse/label/null0.25.0

Resources

NameType
aws_cloudfront_distribution.defaultresource
aws_cloudfront_origin_access_control.defaultresource
aws_cloudfront_origin_access_identity.defaultresource
aws_s3_bucket.originresource
aws_s3_bucket_acl.originresource
aws_s3_bucket_cors_configuration.originresource
aws_s3_bucket_ownership_controls.originresource
aws_s3_bucket_policy.defaultresource
aws_s3_bucket_public_access_block.originresource
aws_s3_bucket_server_side_encryption_configuration.originresource
aws_s3_bucket_versioning.originresource
random_password.refererresource
time_sleep.wait_for_aws_s3_bucket_settingsresource
aws_caller_identity.currentdata source
aws_iam_policy_document.combineddata source
aws_iam_policy_document.deploymentdata source
aws_iam_policy_document.s3_origin_access_controldata source
aws_iam_policy_document.s3_origin_access_identitydata source
aws_iam_policy_document.s3_ssl_onlydata source
aws_iam_policy_document.s3_website_origindata source
aws_partition.currentdata source
aws_region.currentdata source
aws_s3_bucket.cf_logsdata source
aws_s3_bucket.origindata source

Inputs

NameDescriptionTypeDefaultRequired
<a name="input_access_log_bucket_name"></a> access_log_bucket_nameDEPRECATED. Use s3_access_log_bucket_name instead.stringnullno
<a name="input_acm_certificate_arn"></a> acm_certificate_arnExisting ACM Certificate ARNstring""no
<a name="input_additional_bucket_policy"></a> additional_bucket_policyAdditional 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.<br/>It is also possible to override the default policy statements by providing statements with S3GetObjectForCloudFront and S3ListBucketForCloudFront sid.string"{}"no
<a name="input_additional_tag_map"></a> additional_tag_mapAdditional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.<br/>This is for some rare cases where resources want additional configuration of tags<br/>and therefore take a list of maps with tag key, value, and additional configuration.map(string){}no
<a name="input_aliases"></a> aliasesList of FQDN's - Used to set the Alternate Domain Names (CNAMEs) setting on Cloudfrontlist(string)[]no
<a name="input_allow_ssl_requests_only"></a> allow_ssl_requests_onlySet to true to require requests to use Secure Socket Layer (HTTPS/SSL). This will explicitly deny access to HTTP requestsbooltrueno
<a name="input_allowed_methods"></a> allowed_methodsList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFrontlist(string)<pre>[<br/> "DELETE",<br/> "GET",<br/> "HEAD",<br/> "OPTIONS",<br/> "PATCH",<br/> "POST",<br/> "PUT"<br/>]</pre>no
<a name="input_attributes"></a> attributesID element. Additional attributes (e.g. workers or cluster) to add to id,<br/>in the order they appear in the list. New attributes are appended to the<br/>end of the list. The elements of the list are joined by the delimiter<br/>and treated as a single ID element.list(string)[]no
<a name="input_block_origin_public_access_enabled"></a> block_origin_public_access_enabledWhen set to 'true' the s3 origin bucket will have public access block enabledboolfalseno
<a name="input_bucket_versioning"></a> bucket_versioningState of bucket versioning optionstring"Disabled"no
<a name="input_cache_policy_id"></a> cache_policy_idThe unique identifier of the existing cache policy to attach to the default cache behavior.<br/>If not provided, this module will add a default cache policy using other provided inputs.stringnullno
<a name="input_cached_methods"></a> cached_methodsList of cached methods (e.g. GET, PUT, POST, DELETE, HEAD)list(string)<pre>[<br/> "GET",<br/> "HEAD"<br/>]</pre>no
<a name="input_cloudfront_access_log_bucket_name"></a> cloudfront_access_log_bucket_nameWhen cloudfront_access_log_create_bucket is false, this is the name of the existing S3 Bucket where<br/>Cloudfront Access Logs are to be delivered and is required. IGNORED when cloudfront_access_log_create_bucket is true.string""no
<a name="input_cloudfront_access_log_create_bucket"></a> cloudfront_access_log_create_bucketWhen true and cloudfront_access_logging_enabled is also true, this module will create a new,<br/>separate S3 bucket to receive Cloudfront Access Logs.booltrueno
<a name="input_cloudfront_access_log_include_cookies"></a> cloudfront_access_log_include_cookiesSet true to include cookies in Cloudfront Access Logsboolfalseno
<a name="input_cloudfront_access_log_prefix"></a> cloudfront_access_log_prefixPrefix to use for Cloudfront Access Log object keys. Defaults to no prefix.string""no
<a name="input_cloudfront_access_logging_enabled"></a> cloudfront_access_logging_enabledSet true to enable delivery of Cloudfront Access Logs to an S3 bucketbooltrueno
<a name="input_cloudfront_origin_access_control_id"></a> cloudfront_origin_access_control_idCloudFront 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.string""no
<a name="input_cloudfront_origin_access_identity_iam_arn"></a> cloudfront_origin_access_identity_iam_arnExisting cloudfront origin access identity iam arn that is supplied in the s3 bucket policystring""no
<a name="input_cloudfront_origin_access_identity_path"></a> cloudfront_origin_access_identity_pathExisting cloudfront origin access identity path used in the cloudfront distribution's s3_origin_config contentstring""no
<a name="input_comment"></a> commentComment for the CloudFront distributionstring"Managed by Terraform"no
<a name="input_compress"></a> compressCompress content for web requests that include Accept-Encoding: gzip in the request headerbooltrueno
<a name="input_context"></a> contextSingle object for setting entire context at once.<br/>See description of individual variables for details.<br/>Leave string and numeric variables as null to use default value.<br/>Individual variable settings (non-null) override settings in context object,<br/>except for attributes, tags, and additional_tag_map, which are merged.any<pre>{<br/> "additional_tag_map": {},<br/> "attributes": [],<br/> "delimiter": null,<br/> "descriptor_formats": {},<br/> "enabled": true,<br/> "environment": null,<br/> "id_length_limit": null,<br/> "label_key_case": null,<br/> "label_order": [],<br/> "label_value_case": null,<br/> "labels_as_tags": [<br/> "unset"<br/> ],<br/> "name": null,<br/> "namespace": null,<br/> "regex_replace_chars": null,<br/> "stage": null,<br/> "tags": {},<br/> "tenant": null<br/>}</pre>no
<a name="input_cors_allowed_headers"></a> cors_allowed_headersList of allowed headers for S3 bucketlist(string)<pre>[<br/> "*"<br/>]</pre>no
<a name="input_cors_allowed_methods"></a> cors_allowed_methodsList of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for S3 bucketlist(string)<pre>[<br/> "GET"<br/>]</pre>no
<a name="input_cors_allowed_origins"></a> cors_allowed_originsList of allowed origins (e.g. example.com, test.com) for S3 bucketlist(string)[]no
<a name="input_cors_expose_headers"></a> cors_expose_headersList of expose header in the response for S3 bucketlist(string)<pre>[<br/> "ETag"<br/>]</pre>no
<a name="input_cors_max_age_seconds"></a> cors_max_age_secondsTime in seconds that browser can cache the response for S3 bucketnumber3600no
<a name="input_custom_error_response"></a> custom_error_responseList of one or more custom error response element maps<pre>list(object({<br/> error_caching_min_ttl = string<br/> error_code = string<br/> response_code = string<br/> response_page_path = string<br/> }))</pre>[]no
<a name="input_custom_origin_headers"></a> custom_origin_headersA list of origin header parameters that will be sent to originlist(object({ name = string, value = string }))[]no
<a name="input_custom_origins"></a> custom_originsA list of additional custom website origins for this distribution.<br/>The origin_access_control_id field specifies the Origin Access Control configuration to use for this origin.<br/>This is used to configure secure access between CloudFront and the origin.<pre>list(object({<br/> domain_name = string<br/> origin_id = string<br/> origin_path = string<br/> origin_access_control_id = optional(string)<br/> custom_headers = list(object({<br/> name = string<br/> value = string<br/> }))<br/> custom_origin_config = object({<br/> http_port = number<br/> https_port = number<br/> origin_protocol_policy = string<br/> origin_ssl_protocols = list(string)<br/> origin_keepalive_timeout = number<br/> origin_read_timeout = number<br/> })<br/> }))</pre>[]no
<a name="input_default_root_object"></a> default_root_objectObject that CloudFront return when requests the root URLstring"index.html"no
<a name="input_default_ttl"></a> default_ttlDefault amount of time (in seconds) that an object is in a CloudFront cachenumber60no
<a name="input_delimiter"></a> delimiterDelimiter to be used between ID elements.<br/>Defaults to - (hyphen). Set to "" to use no delimiter at all.stringnullno
<a name="input_deployment_actions"></a> deployment_actionsList of actions to permit deployment_principal_arns to perform on bucket and bucket prefixes (see deployment_principal_arns)list(string)<pre>[<br/> "s3:PutObject",<br/> "s3:PutObjectAcl",<br/> "s3:GetObject",<br/> "s3:DeleteObject",<br/> "s3:ListBucket",<br/> "s3:ListBucketMultipartUploads",<br/> "s3:GetBucketLocation",<br/> "s3:AbortMultipartUpload"<br/>]</pre>no
<a name="input_deployment_principal_arns"></a> deployment_principal_arns(Optional) Map of IAM Principal ARNs to lists of S3 path prefixes to grant deployment_actions permissions.<br/>Resource list will include the bucket itself along with all the prefixes. Prefixes should not begin with '/'.map(list(string)){}no
<a name="input_descriptor_formats"></a> descriptor_formatsDescribe additional descriptors to be output in the descriptors output map.<br/>Map of maps. Keys are names of descriptors. Values are maps of the form<br/>{<br/> format = string<br/> labels = list(string)<br/>}<br/>(Type is any so the map values can later be enhanced to provide additional options.)<br/>format is a Terraform format string to be passed to the format() function.<br/>labels is a list of labels, in order, to pass to format() function.<br/>Label values will be normalized before being passed to format() so they will be<br/>identical to how they appear in id.<br/>Default is {} (descriptors output will be empty).any{}no
<a name="input_distribution_enabled"></a> distribution_enabledSet to false to create the distribution but still prevent CloudFront from serving requests.booltrueno
<a name="input_dns_alias_enabled"></a> dns_alias_enabledCreate a DNS alias for the CDN. Requires parent_zone_id or parent_zone_nameboolfalseno
<a name="input_dns_allow_overwrite"></a> dns_allow_overwriteAllow 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 environmentsboolfalseno
<a name="input_enabled"></a> enabledSet to false to prevent the module from creating any resourcesboolnullno
<a name="input_encryption_enabled"></a> encryption_enabledWhen set to 'true' the resource will have aes256 encryption enabled by defaultbooltrueno
<a name="input_environment"></a> environmentID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'stringnullno
<a name="input_error_document"></a> error_documentAn absolute path to the document to return in case of a 4XX errorstring""no
<a name="input_external_aliases"></a> external_aliasesList of FQDN's - Used to set the Alternate Domain Names (CNAMEs) setting on Cloudfront. No new route53 records will be created for theselist(string)[]no
<a name="input_extra_logs_attributes"></a> extra_logs_attributesAdditional attributes to add to the end of the generated Cloudfront Access Log S3 Bucket name.<br/>Only effective if cloudfront_access_log_create_bucket is true.list(string)<pre>[<br/> "logs"<br/>]</pre>no
<a name="input_extra_origin_attributes"></a> extra_origin_attributesAdditional attributes to put onto the origin labellist(string)<pre>[<br/> "origin"<br/>]</pre>no
<a name="input_forward_cookies"></a> forward_cookiesSpecifies whether you want CloudFront to forward all or no cookies to the origin. Can be 'all' or 'none'string"none"no
<a name="input_forward_header_values"></a> forward_header_valuesA list of whitelisted header values to forward to the origin (incompatible with cache_policy_id)list(string)<pre>[<br/> "Access-Control-Request-Headers",<br/> "Access-Control-Request-Method",<br/> "Origin"<br/>]</pre>no
<a name="input_forward_query_string"></a> forward_query_stringForward query strings to the origin that is associated with this cache behavior (incompatible with cache_policy_id)boolfalseno
<a name="input_function_association"></a> function_associationA config block that triggers a CloudFront function with specific actions.<br/>See the aws_cloudfront_distribution<br/>documentation for more information.<pre>list(object({<br/> event_type = string<br/> function_arn = string<br/> }))</pre>[]no
<a name="input_geo_restriction_locations"></a> geo_restriction_locationsList of country codes for which CloudFront either to distribute content (whitelist) or not distribute your content (blacklist)list(string)[]no
<a name="input_geo_restriction_type"></a> geo_restriction_typeMethod that use to restrict distribution of your content by country: none, whitelist, or blackliststring"none"no
<a name="input_http_version"></a> http_versionThe maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3 and http3string"http2"no
<a name="input_id_length_limit"></a> id_length_limitLimit id to this many characters (minimum 6).<br/>Set to 0 for unlimited length.<br/>Set to null for keep the existing setting, which defaults to 0.<br/>Does not affect id_full.numbernullno
<a name="input_index_document"></a> index_documentAmazon S3 returns this index document when requests are made to the root domain or any of the subfoldersstring"index.html"no
<a name="input_ipv6_enabled"></a> ipv6_enabledSet to true to enable an AAAA DNS record to be set as well as the A recordbooltrueno
<a name="input_label_key_case"></a> label_key_caseControls the letter case of the tags keys (label names) for tags generated by this module.<br/>Does not affect keys of tags passed in via the tags input.<br/>Possible values: lower, title, upper.<br/>Default value: title.stringnullno
<a name="input_label_order"></a> label_orderThe order in which the labels (ID elements) appear in the id.<br/>Defaults to ["namespace", "environment", "stage", "name", "attributes"].<br/>You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.list(string)nullno
<a name="input_label_value_case"></a> label_value_caseControls the letter case of ID elements (labels) as included in id,<br/>set as tag values, and output by this module individually.<br/>Does not affect values of tags passed in via the tags input.<br/>Possible values: lower, title, upper and none (no transformation).<br/>Set this to title and set delimiter to "" to yield Pascal Case IDs.<br/>Default value: lower.stringnullno
<a name="input_labels_as_tags"></a> labels_as_tagsSet of labels (ID elements) to include as tags in the tags output.<br/>Default is to include all labels.<br/>Tags with empty values will not be included in the tags output.<br/>Set to [] to suppress all generated tags.<br/>Notes:<br/> The value of the name tag, if included, will be the id, not the name.<br/> Unlike other null-label inputs, the initial setting of labels_as_tags cannot be<br/> changed in later chained modules. Attempts to change it will be silently ignored.set(string)<pre>[<br/> "default"<br/>]</pre>no
<a name="input_lambda_function_association"></a> lambda_function_associationA config block that triggers a lambda@edge function with specific actions<pre>list(object({<br/> event_type = string<br/> include_body = bool<br/> lambda_arn = string<br/> }))</pre>[]no
<a name="input_log_expiration_days"></a> log_expiration_daysNumber of days after object creation to expire Cloudfront Access Log objects.<br/>Only effective if cloudfront_access_log_create_bucket is true.number90no
<a name="input_log_glacier_transition_days"></a> log_glacier_transition_daysNumber of days after object creation to move Cloudfront Access Log objects to the glacier tier.<br/>Only effective if cloudfront_access_log_create_bucket is true.number60no
<a name="input_log_include_cookies"></a> log_include_cookiesDEPRECATED. Use cloudfront_access_log_include_cookies instead.boolnullno
<a name="input_log_prefix"></a> log_prefixDEPRECATED. Use cloudfront_access_log_prefix instead.stringnullno
<a name="input_log_standard_transition_days"></a> log_standard_transition_daysNumber of days after object creation to move Cloudfront Access Log objects to the infrequent access tier.<br/>Only effective if cloudfront_access_log_create_bucket is true.number30no
<a name="input_log_versioning_enabled"></a> log_versioning_enabledSet true to enable object versioning in the created Cloudfront Access Log S3 Bucket.<br/>Only effective if cloudfront_access_log_create_bucket is true.boolfalseno
<a name="input_logging_enabled"></a> logging_enabledDEPRECATED. Use cloudfront_access_logging_enabled instead.boolnullno
<a name="input_max_ttl"></a> max_ttlMaximum amount of time (in seconds) that an object is in a CloudFront cachenumber31536000no
<a name="input_min_ttl"></a> min_ttlMinimum amount of time that you want objects to stay in CloudFront cachesnumber0no
<a name="input_minimum_protocol_version"></a> minimum_protocol_versionCloudfront TLS minimum protocol version.<br/>If var.acm_certificate_arn is unset, only "TLSv1" can be specified. See: AWS Cloudfront create-distribution documentation<br/>and Supported protocols and ciphers between viewers and CloudFront for more information.<br/>Defaults to "TLSv1.2_2019" unless var.acm_certificate_arn is unset, in which case it defaults to TLSv1string""no
<a name="input_name"></a> nameID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.<br/>This is the only ID element not also included as a tag.<br/>The "name" tag is set to the full id string. There is no tag with the value of the name input.stringnullno
<a name="input_namespace"></a> namespaceID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally uniquestringnullno
<a name="input_ordered_cache"></a> ordered_cacheAn ordered list of cache behaviors resource for this distribution.<br/>List in order of precedence (first match wins). This is in addition to the default cache policy.<br/>Set target_origin_id to "" to specify the S3 bucket origin created by this module.<pre>list(object({<br/> target_origin_id = string<br/> path_pattern = string<br/><br/> allowed_methods = list(string)<br/> cached_methods = list(string)<br/> compress = bool<br/> trusted_signers = list(string)<br/> trusted_key_groups = list(string)<br/><br/> cache_policy_id = string<br/> origin_request_policy_id = string<br/> realtime_log_config_arn = optional(string)<br/><br/> viewer_protocol_policy = string<br/> min_ttl = number<br/> default_ttl = number<br/> max_ttl = number<br/> response_headers_policy_id = string<br/><br/> forward_query_string = bool<br/> forward_header_values = list(string)<br/> forward_cookies = string<br/> forward_cookies_whitelisted_names = list(string)<br/><br/> lambda_function_association = list(object({<br/> event_type = string<br/> include_body = bool<br/> lambda_arn = string<br/> }))<br/><br/> function_association = list(object({<br/> event_type = string<br/> function_arn = string<br/> }))<br/> }))</pre>[]no
<a name="input_origin_access_control_signing_behavior"></a> origin_access_control_signing_behaviorSpecifies which requests CloudFront signs. Specify always for the most common use case. Allowed values: always, never, and no-override.string"always"no
<a name="input_origin_access_type"></a> origin_access_typeChoose to use origin_access_control or orgin_access_identitystring"origin_access_identity"no
<a name="input_origin_bucket"></a> origin_bucketName 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 inputsstringnullno
<a name="input_origin_force_destroy"></a> origin_force_destroyDelete all objects from the bucket so that the bucket can be destroyed without error (e.g. true or false)boolfalseno
<a name="input_origin_groups"></a> origin_groupsList of Origin Groups to create in the distribution.<br/>The values of primary_origin_id and failover_origin_id must correspond to origin IDs existing in var.s3_origins or var.custom_origins.<br/><br/>If primary_origin_id is set to null or "", then the origin id of the origin created by this module will be used in its place.<br/>This is to allow for the use case of making the origin created by this module the primary origin in an origin group.<pre>list(object({<br/> primary_origin_id = string<br/> failover_origin_id = string<br/> failover_criteria = list(string)<br/> }))</pre>[]no
<a name="input_origin_path"></a> 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
<a name="input_origin_request_policy_id"></a> origin_request_policy_idThe unique identifier of the origin request policy that is attached to the behavior.<br/>Should be used in conjunction with cache_policy_id.stringnullno
<a name="input_origin_shield_enabled"></a> origin_shield_enabledIf enabled, origin shield will be enabled for the default originboolfalseno
<a name="input_origin_ssl_protocols"></a> origin_ssl_protocolsThe SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPS.list(string)<pre>[<br/> "TLSv1",<br/> "TLSv1.1",<br/> "TLSv1.2"<br/>]</pre>no
<a name="input_override_origin_bucket_policy"></a> override_origin_bucket_policyWhen using an existing origin bucket (through var.origin_bucket), setting this to 'false' will make it so the existing bucket policy will not be overridenbooltrueno
<a name="input_parent_zone_id"></a> parent_zone_idID of the hosted zone to contain this record (or specify parent_zone_name). Requires dns_alias_enabled set to truestringnullno
<a name="input_parent_zone_name"></a> parent_zone_nameName of the hosted zone to contain this record (or specify parent_zone_id). Requires dns_alias_enabled set to truestring""no
<a name="input_price_class"></a> price_classPrice class for this distribution: PriceClass_All, PriceClass_200, PriceClass_100string"PriceClass_100"no
<a name="input_query_string_cache_keys"></a> query_string_cache_keysWhen forward_query_string is enabled, only the query string keys listed in this argument are cached (incompatible with cache_policy_id)list(string)[]no
<a name="input_realtime_log_config_arn"></a> realtime_log_config_arnThe ARN of the real-time log configuration that is attached to this cache behaviorstringnullno
<a name="input_redirect_all_requests_to"></a> redirect_all_requests_toA hostname to redirect all website requests for this distribution to. If this is set, it overrides other website settingsstring""no
<a name="input_regex_replace_chars"></a> regex_replace_charsTerraform regular expression (regex) string.<br/>Characters matching the regex will be removed from the ID elements.<br/>If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.stringnullno
<a name="input_response_headers_policy_id"></a> response_headers_policy_idThe identifier for a response headers policystring""no
<a name="input_routing_rules"></a> routing_rulesA json array containing routing rules describing redirect behavior and when redirects are appliedstring""no
<a name="input_s3_access_log_bucket_name"></a> s3_access_log_bucket_nameName of the existing S3 bucket where S3 Access Logs will be delivered. Default is not to enable S3 Access Logging.string""no
<a name="input_s3_access_log_prefix"></a> s3_access_log_prefixPrefix to use for S3 Access Log object keys. Defaults to logs/${module.this.id}string""no
<a name="input_s3_access_logging_enabled"></a> s3_access_logging_enabledSet true to deliver S3 Access Logs to the s3_access_log_bucket_name bucket.<br/>Defaults to false if s3_access_log_bucket_name is empty (the default), true otherwise.<br/>Must be set explicitly if the access log bucket is being created at the same time as this module is being invoked.boolnullno
<a name="input_s3_object_ownership"></a> s3_object_ownershipSpecifies the S3 object ownership control on the origin bucket. Valid values are ObjectWriter, BucketOwnerPreferred, and 'BucketOwnerEnforced'.string"ObjectWriter"no
<a name="input_s3_origins"></a> s3_originsA list of S3 origins (in addition to the one created by this module) for this distribution.<br/>S3 buckets configured as websites are custom_origins, not s3_origins.<br/>Specifying s3_origin_config.origin_access_identity as null or "" will have it translated to the origin_access_identity used by the origin created by the module.<pre>list(object({<br/> domain_name = string<br/> origin_id = string<br/> origin_path = string<br/> origin_access_control_id = string<br/> s3_origin_config = object({<br/> origin_access_identity = string<br/> })<br/> }))</pre>[]no
<a name="input_s3_website_password_enabled"></a> s3_website_password_enabledIf set to true, and website_enabled is also true, a password will be required in the Referrer field of the<br/>HTTP request in order to access the website, and Cloudfront will be configured to pass this password in its requests.<br/>This will make it much harder for people to bypass Cloudfront and access the S3 website directly via its website endpoint.boolfalseno
<a name="input_stage"></a> stageID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'stringnullno
<a name="input_tags"></a> tagsAdditional tags (e.g. {'BusinessUnit': 'XYZ'}).<br/>Neither the tag keys nor the tag values will be modified by this module.map(string){}no
<a name="input_tenant"></a> tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
<a name="input_trusted_key_groups"></a> trusted_key_groupsA list of key group IDs that CloudFront can use to validate signed URLs or signed cookies.list(string)[]no
<a name="input_trusted_signers"></a> trusted_signersThe AWS accounts, if any, that you want to allow to create signed URLs for private content. 'self' is acceptable.list(string)[]no
<a name="input_versioning_enabled"></a> versioning_enabledWhen set to 'true' the s3 origin bucket will have versioning enabledbooltrueno
<a name="input_viewer_protocol_policy"></a> viewer_protocol_policyLimit the protocol users can use to access content. One of allow-all, https-only, or redirect-to-httpsstring"redirect-to-https"no
<a name="input_wait_for_deployment"></a> wait_for_deploymentWhen set to 'true' the resource will wait for the distribution status to change from InProgress to Deployedbooltrueno
<a name="input_web_acl_id"></a> web_acl_idID of the AWS WAF web ACL that is associated with the distributionstring""no
<a name="input_website_enabled"></a> website_enabledSet to true to enable the created S3 bucket to serve as a website independently of Cloudfront,<br/>and to use that website as the origin. See the README for details and caveats. See also s3_website_password_enabled.boolfalseno

Outputs

NameDescription
<a name="output_aliases"></a> aliasesAliases of the CloudFront distribution.
<a name="output_cf_access_control_id"></a> cf_access_control_idCloudFront Origin Access Control ID
<a name="output_cf_arn"></a> cf_arnARN of AWS CloudFront distribution
<a name="output_cf_domain_name"></a> cf_domain_nameDomain name corresponding to the distribution
<a name="output_cf_etag"></a> cf_etagCurrent version of the distribution's information
<a name="output_cf_hosted_zone_id"></a> cf_hosted_zone_idCloudFront Route 53 zone ID
<a name="output_cf_id"></a> cf_idID of AWS CloudFront distribution
<a name="output_cf_identity_iam_arn"></a> cf_identity_iam_arnCloudFront Origin Access Identity IAM ARN
<a name="output_cf_origin_groups"></a> cf_origin_groupsList of Origin Groups in the CloudFront distribution.
<a name="output_cf_origin_ids"></a> cf_origin_idsList of Origin IDs in the CloudFront distribution.
<a name="output_cf_primary_origin_id"></a> cf_primary_origin_idThe ID of the origin created by this module.
<a name="output_cf_s3_canonical_user_id"></a> cf_s3_canonical_user_idCanonical user ID for CloudFront Origin Access Identity
<a name="output_cf_status"></a> cf_statusCurrent status of the distribution
<a name="output_logs"></a> logsLog bucket resource
<a name="output_s3_bucket"></a> s3_bucketName of origin S3 bucket
<a name="output_s3_bucket_arn"></a> s3_bucket_arnARN of origin S3 bucket
<a name="output_s3_bucket_domain_name"></a> s3_bucket_domain_nameDomain of origin S3 bucket
<a name="output_s3_bucket_policy"></a> s3_bucket_policyFinal computed S3 bucket policy
<!-- markdownlint-restore -->

Related Projects

Check out these related projects.

[!TIP]

Use Terraform Reference Architectures for AWS

Use Cloud Posse's ready-to-go terraform architecture blueprints for AWS to get up and running quickly.

βœ… We build it together with your team.<br/> βœ… Your team owns everything.<br/> βœ… 100% Open Source and backed by fanatical support.<br/>

<a href="https://cpco.io/commercial-support?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-cloudfront-s3-cdn&utm_content=commercial_support"><img alt="Request Quote" src="https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge"/></a>

<details><summary>πŸ“š <strong>Learn More</strong></summary> <br/>

Cloud Posse is the leading DevOps Accelerator for funded startups and enterprises.

Your team can operate like a pro today.

Ensure that your team succeeds by using Cloud Posse's proven process and turnkey blueprints. Plus, we stick around until you succeed.

Day-0: Your Foundation for Success

<a href="https://cpco.io/commercial-support?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-cloudfront-s3-cdn&utm_content=commercial_support"><img alt="Request Quote" src="https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge"/></a>

Day-2: Your Operational Mastery

<a href="https://cpco.io/commercial-support?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-cloudfront-s3-cdn&utm_content=commercial_support"><img alt="Request Quote" src="https://img.shields.io/badge/request%20quote-success.svg?style=for-the-badge"/></a>

</details>

✨ Contributing

This project is under active development, and we encourage contributions from our community.

Many thanks to our outstanding contributors:

<a href="https://github.com/cloudposse/terraform-aws-cloudfront-s3-cdn/graphs/contributors"> <img src="https://contrib.rocks/image?repo=cloudposse/terraform-aws-cloudfront-s3-cdn&max=24" /> </a>

For πŸ› bug reports & feature requests, please use the issue tracker.

In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

  1. Review our Code of Conduct and Contributor Guidelines.
  2. Fork the repo on GitHub
  3. Clone the project to your own machine
  4. Commit changes to your own branch
  5. Push your work back up to your fork
  6. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!

🌎 Slack Community

Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

πŸ“° Newsletter

Sign up for our newsletter and join 3,000+ DevOps engineers, CTOs, and founders who get insider access to the latest DevOps trends, so you can always stay in the know. Dropped straight into your Inbox every week β€” and usually a 5-minute read.

πŸ“† Office Hours <a href="https://cloudposse.com/office-hours?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-cloudfront-s3-cdn&utm_content=office_hours"><img src="https://img.cloudposse.com/fit-in/200x200/https://cloudposse.com/wp-content/uploads/2019/08/Powered-by-Zoom.png" align="right" /></a>

Join us every Wednesday via Zoom for your weekly dose of insider DevOps trends, AWS news and Terraform insights, all sourced from our SweetOps community, plus a live Q&A that you can’t find anywhere else. It's FREE for everyone!

License

<a href="https://opensource.org/licenses/Apache-2.0"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=for-the-badge" alt="License"></a>

<details> <summary>Preamble to the Apache License, Version 2.0</summary> <br/> <br/>

Complete license is available in the LICENSE file.

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
</details>

Trademarks

All other trademarks referenced herein are the property of their respective owners.


Copyright Β© 2017-2024 Cloud Posse, LLC

<a href="https://cloudposse.com/readme/footer/link?utm_source=github&utm_medium=readme&utm_campaign=cloudposse/terraform-aws-cloudfront-s3-cdn&utm_content=readme_footer_link"><img alt="README footer" src="https://cloudposse.com/readme/footer/img"/></a>

<img alt="Beacon" width="0" src="https://ga-beacon.cloudposse.com/UA-76589703-4/cloudposse/terraform-aws-cloudfront-s3-cdn?pixel&cs=github&cm=readme&an=terraform-aws-cloudfront-s3-cdn"/>