Git Product home page Git Product logo

terraform-aws-cloudfront-cdn's Introduction

Project Banner

Latest ReleaseLast UpdatedSlack Community

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.

Tip

๐Ÿ‘ฝ Use Atmos with Terraform

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

Watch demo of using Atmos with Terraform
Example of running atmos to manage infrastructure from our Quick Start tutorial.

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

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.

Makefile Targets

Available targets:

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

Requirements

Name Version
terraform >= 1.0
aws >= 4.9.0
local >= 1.2

Providers

Name Version
aws >= 4.9.0

Modules

Name Source Version
dns cloudposse/route53-alias/aws 0.13.0
logs cloudposse/s3-log-storage/aws 1.4.2
origin_label cloudposse/label/null 0.25.0
this cloudposse/label/null 0.25.0

Resources

Name Type
aws_cloudfront_distribution.default resource
aws_cloudfront_origin_access_identity.default resource

Inputs

Name Description Type Default Required
acm_certificate_arn Existing ACM Certificate ARN string "" no
additional_tag_map 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.
map(string) {} no
aliases List of aliases. CAUTION! Names MUSTN'T contain trailing . list(string) [] no
allowed_methods List of allowed methods (e.g. GET, PUT, POST, DELETE, HEAD) for AWS CloudFront list(string)
[
"DELETE",
"GET",
"HEAD",
"OPTIONS",
"PATCH",
"POST",
"PUT"
]
no
attributes 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.
list(string) [] no
cache_policy_id ID of the cache policy attached to the cache behavior string null no
cached_methods List of cached methods (e.g. GET, PUT, POST, DELETE, HEAD) list(string)
[
"GET",
"HEAD"
]
no
comment Comment for the origin access identity string "Managed by Terraform" no
compress Whether you want CloudFront to automatically compress content for web requests that include Accept-Encoding: gzip in the request header (default: false) bool false no
context 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.
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_response List 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_header List of one or more custom headers passed to the origin
list(object({
name = string
value = string
}))
[] no
custom_origins 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
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_object Object that CloudFront return when requests the root URL string "index.html" no
default_ttl Default amount of time (in seconds) that an object is in a CloudFront cache number 60 no
delimiter Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
string null no
descriptor_formats 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).
any {} no
distribution_enabled 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. bool true no
dns_aliases_enabled Set to false to prevent dns records for aliases from being created bool true no
enabled Set to false to prevent the module from creating any resources bool null no
environment ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' string null no
forward_cookies Specifies whether you want CloudFront to forward cookies to the origin. Valid options are all, none or whitelist string "none" no
forward_cookies_whitelisted_names List of forwarded cookie names list(string) [] no
forward_headers Specifies 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_string Forward query strings to the origin that is associated with this cache behavior bool false no
function_association A 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_locations List of country codes for which CloudFront either to distribute content (whitelist) or not distribute your content (blacklist) list(string) [] no
geo_restriction_type Method that use to restrict distribution of your content by country: none, whitelist, or blacklist string "none" no
http_version The maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3 and http3. string "http2" no
id_length_limit 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.
number null no
is_ipv6_enabled State of CloudFront IPv6 bool true no
label_key_case 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.
string null no
label_order 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.
list(string) null no
label_value_case 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.
string null no
labels_as_tags 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.
set(string)
[
"default"
]
no
lambda_function_association A 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_fqdn Optional fqdn of logging bucket, if not supplied a bucket will be generated. string "" no
log_expiration_days Number of days after which to expunge the objects number 90 no
log_force_destroy 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. bool false no
log_glacier_transition_days Number of days after which to move the data to the glacier storage tier number 60 no
log_include_cookies Include cookies in access logs bool false no
log_prefix Path of logs in S3 bucket string "" no
log_standard_transition_days Number of days to persist in the standard storage tier before moving to the glacier tier number 30 no
logging_enabled When true, access logs will be sent to a newly created s3 bucket bool true no
max_ttl Maximum amount of time (in seconds) that an object is in a CloudFront cache number 31536000 no
min_ttl Minimum amount of time that you want objects to stay in CloudFront caches number 0 no
name 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.
string null no
namespace ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique string null no
ordered_cache 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.
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_enabled When true, creates origin access identity resource bool true no
origin_domain_name The DNS domain name of your custom origin (e.g. website) string "" no
origin_http_port The HTTP port the custom origin listens on number "80" no
origin_https_port The HTTPS port the custom origin listens on number 443 no
origin_keepalive_timeout The Custom KeepAlive timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase. number 60 no
origin_path 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. string "" no
origin_protocol_policy The origin protocol policy to apply to your origin. One of http-only, https-only, or match-viewer string "match-viewer" no
origin_read_timeout The Custom Read timeout, in seconds. By default, AWS enforces a limit of 60. But you can request an increase. number 60 no
origin_request_policy_id ID of the origin request policy attached to the cache behavior string null no
origin_shield The CloudFront Origin Shield settings
object({
enabled = bool
region = string
})
null no
origin_ssl_protocols The SSL/TLS protocols that you want CloudFront to use when communicating with your origin over HTTPS list(string)
[
"TLSv1",
"TLSv1.1",
"TLSv1.2"
]
no
parent_zone_id ID of the hosted zone to contain this record (or specify parent_zone_name) string "" no
parent_zone_name Name of the hosted zone to contain this record (or specify parent_zone_id) string "" no
price_class Price class for this distribution: PriceClass_All, PriceClass_200, PriceClass_100 string "PriceClass_100" no
realtime_log_config_arn The ARN of the real-time log configuration that is attached to this cache behavior string null no
regex_replace_chars 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.
string null no
response_headers_policy_id The identifier for a response headers policy string "" no
stage ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' string null no
tags Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string) {} no
tenant ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for string null no
trusted_signers List of AWS account IDs (or self) that you want to allow to create signed URLs for private content list(string) [] no
viewer_minimum_protocol_version 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. string "TLSv1.2_2021" no
viewer_protocol_policy allow-all, redirect-to-https string "redirect-to-https" no
web_acl_id ID of the AWS WAF web ACL that is associated with the distribution string "" no

Outputs

Name Description
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

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.
โœ… Your team owns everything.
โœ… 100% Open Source and backed by fanatical support.

Request Quote

๐Ÿ“š Learn More

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

  • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
  • Deployment Strategy. Adopt a proven deployment strategy with GitHub Actions, enabling automated, repeatable, and reliable software releases.
  • Site Reliability Engineering. Gain total visibility into your applications and services with Datadog, ensuring high availability and performance.
  • Security Baseline. Establish a secure environment from the start, with built-in governance, accountability, and comprehensive audit logs, safeguarding your operations.
  • GitOps. Empower your team to manage infrastructure changes confidently and efficiently through Pull Requests, leveraging the full power of GitHub Actions.

Request Quote

Day-2: Your Operational Mastery

  • Training. Equip your team with the knowledge and skills to confidently manage the infrastructure, ensuring long-term success and self-sufficiency.
  • Support. Benefit from a seamless communication over Slack with our experts, ensuring you have the support you need, whenever you need it.
  • Troubleshooting. Access expert assistance to quickly resolve any operational challenges, minimizing downtime and maintaining business continuity.
  • Code Reviews. Enhance your teamโ€™s code quality with our expert feedback, fostering continuous improvement and collaboration.
  • Bug Fixes. Rely on our team to troubleshoot and resolve any issues, ensuring your systems run smoothly.
  • Migration Assistance. Accelerate your migration process with our dedicated support, minimizing disruption and speeding up time-to-value.
  • Customer Workshops. Engage with our team in weekly workshops, gaining insights and strategies to continuously improve and innovate.

Request Quote

โœจ Contributing

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

Many thanks to our outstanding contributors:

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

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

License

Preamble to the Apache License, Version 2.0

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.

Trademarks

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


Copyright ยฉ 2017-2024 Cloud Posse, LLC

README footer

Beacon

terraform-aws-cloudfront-cdn's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terraform-aws-cloudfront-cdn's Issues

Enabled input variable doesn't actually prevent resource creation

The README documents the follow behaviour for the enabled input variable:

Name Description Type Default Required
enabled Set to false to prevent the module from creating any resources string true no

However when actually using this variable, all resources for this module are still created. On inspection of the main.tf file, it shows that this variable is actually only used to set the enabled status on a CloudFront distribution.

Ideally the input variable should be updated to actually work as documented, or at the very least the README documentation + variables.tf descriptions should be updated to represent what they actually do.

support terraform 0.12

terraform init --upgrade
Upgrading modules...
Downloading git::https://github.com/cloudposse/terraform-aws-cloudfront-cdn.git?ref=0.7.0 for cdn...
- cdn in .terraform/modules/cdn
Downloading git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.3.7 for cdn.distribution_label...
- cdn.distribution_label in .terraform/modules/cdn.distribution_label
Downloading git::https://github.com/cloudposse/terraform-aws-route53-alias.git?ref=tags/0.2.5 for cdn.dns...
- cdn.dns in .terraform/modules/cdn.dns
Downloading git::https://github.com/cloudposse/terraform-aws-log-storage.git?ref=tags/0.2.2 for cdn.logs...
- cdn.logs in .terraform/modules/cdn.logs
Downloading git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.3.3 for cdn.logs.default_label...
- cdn.logs.default_label in .terraform/modules/cdn.logs.default_label
Downloading git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.3.7 for cdn.origin_label...
- cdn.origin_label in .terraform/modules/cdn.origin_label
Downloading git::https://github.com/cloudposse/terraform-aws-s3-website.git?ref=0.8.0 for website...
- website in .terraform/modules/website
Downloading git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.14.1 for website.default_label...
- website.default_label in .terraform/modules/website.default_label
Downloading git::https://github.com/cloudposse/terraform-aws-route53-alias.git?ref=tags/0.3.0 for website.dns...
- website.dns in .terraform/modules/website.dns
Downloading git::https://github.com/cloudposse/terraform-aws-s3-log-storage.git?ref=tags/0.5.0 for website.logs...
- website.logs in .terraform/modules/website.logs
Downloading git::https://github.com/cloudposse/terraform-null-label.git?ref=tags/0.14.1 for website.logs.default_label...
- website.logs.default_label in .terraform/modules/website.logs.default_label

Initializing the backend...

Initializing provider plugins...
- Checking for available provider plugins...
- Downloading plugin for provider "null" (terraform-providers/null) 2.1.2...
- Downloading plugin for provider "local" (terraform-providers/local) 1.3.0...
- Downloading plugin for provider "aws" (terraform-providers/aws) 2.18.0...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
dhcp-149-171-170-94:infrastructure hachaboob$ terraform apply

Error: Unsupported argument

  on .terraform/modules/cdn/main.tf line 46, in resource "aws_cloudfront_distribution" "default":
  46:   logging_config = {

An argument named "logging_config" is not expected here. Did you mean to
define a block of type "logging_config"?


Error: Incorrect attribute value type

  on .terraform/modules/cdn/main.tf line 52, in resource "aws_cloudfront_distribution" "default":
  52:   aliases = ["${var.aliases}"]

Inappropriate value for attribute "aliases": element 0: string required.


Error: Unsupported argument

  on .terraform/modules/cdn/main.tf line 54, in resource "aws_cloudfront_distribution" "default":
  54:   custom_error_response = ["${var.custom_error_response}"]

An argument named "custom_error_response" is not expected here. Did you mean
to define a block of type "custom_error_response"?


Error: Incorrect attribute value type

  on .terraform/modules/cdn/main.tf line 85, in resource "aws_cloudfront_distribution" "default":
  85:       headers = ["${var.forward_headers}"]

Inappropriate value for attribute "headers": element 0: string required.


Error: Incorrect attribute value type

  on .terraform/modules/cdn/main.tf line 91, in resource "aws_cloudfront_distribution" "default":
  91:         whitelisted_names = ["${var.forward_cookies_whitelisted_names}"]

Inappropriate value for attribute "whitelisted_names": element 0: string
required.


Error: Unsupported argument

  on .terraform/modules/cdn/main.tf line 101, in resource "aws_cloudfront_distribution" "default":
 101:   ordered_cache_behavior = "${var.cache_behavior}"

An argument named "ordered_cache_behavior" is not expected here. Did you mean
to define a block of type "ordered_cache_behavior"?

terraform keeps needing to apply some settings

I have this test config, which seems to work fine:

module "origin" {
  source = "git::https://github.com/cloudposse/terraform-aws-s3-website.git?ref=tags/0.5.1"
  namespace = "ts-web"
  stage = "prod"
  name = "test"

  hostname = "origin.test.catholic.edu"
  parent_zone_name = "catholic.edu"
  cors_allowed_headers = ["*"]
  cors_allowed_methods = ["GET"]
  cors_allowed_origins = ["*"]
  cors_max_age_seconds = "3600"
  cors_expose_headers = ["ETag"]
  force_destroy = "true"
}

resource "aws_s3_bucket_object" "index" {
 bucket       = "${module.origin.hostname}"
 key          = "index.html"
 source       = "${path.module}/index.html"
 content_type = "text/html"
 etag         = "${md5(file("${path.module}/index.html"))}"
 depends_on = ["module.origin"]
}

# CloudFront CDN fronting origin
module "cdn" {
  source = "git::https://github.com/cloudposse/terraform-aws-cloudfront-cdn.git?ref=tags/0.4.0"
  namespace = "ts-web"
  stage = "prod"
  name = "test"

  aliases = ["test.catholic.edu"]
  origin_domain_name = "origin.test.catholic.edu"
  origin_protocol_policy = "http-only"
  parent_zone_name = "catholic.edu"
  acm_certificate_arn = "arn:aws:acm:us-east-1:947556264854:certificate/e9b7a021-ef1a-49f7-8f2c-5a8e13c89dd2"
  forward_cookies = "none"
  forward_headers = ["Origin", "Access-Control-Request-Headers", "Access-Control-Request-Method"]
  default_ttl = 60
  min_ttl = 0
  max_ttl = 86400
  compress = "true"
  cached_methods = ["GET", "HEAD"]
  allowed_methods = ["GET", "HEAD", "OPTIONS"]
  price_class = "PriceClass_All"

But after applying, any new apply attempt shows these changes needed:

~ module.cdn.aws_cloudfront_distribution.default
      default_cache_behavior.0.forwarded_values.0.headers.0: "Access-Control-Request-Headers" => "Origin"
      default_cache_behavior.0.forwarded_values.0.headers.1: "Access-Control-Request-Method" => "Access-Control-Request-Headers"
      default_cache_behavior.0.forwarded_values.0.headers.2: "Origin" => "Access-Control-Request-Method"
      viewer_certificate.0.cloudfront_default_certificate:   "false" => "true"

Support an already created bucket for logging

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

Allow the specification of an existing logging bucket.

Expected Behavior

When a bucket is specified in the input variable the module should not create a bucket

Use Case

Baking in a logging bucket is great, but reduces flexibility, especially where centralised logging is a feature that is wanted (all logs in one central account). Allow a user to specify a bucket by variable and if it is specified stop the resource being created by the module itself.

Describe Ideal Solution

Variable introduced to specify the bucket by a domain name as current code allows and enabled flag should detect whether this is specified and if so set enabled to false on the log bucket resource. If no bucket name is specified (default setting) then current behaviour is maintained.

Alternatives Considered

Have to write my own code and not use this module or fork module and use fork, with the maintenance burden that entails.

Additional Context

N/A

Add support for CloudFront Response Headers Policy

Describe the Feature

AWS CloudFront now supports custom response headers natively without having to set these at origin or set via Lambda.

https://aws.amazon.com/about-aws/whats-new/2021/11/amazon-cloudfront-supports-cors-security-custom-http-response-headers/

This was added to the Hashicorp AWS Provider in 3.64.0
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_response_headers_policy

Please add support for these new data objects within the CDN module, (feature request also created for terraform-aws-cloudfront-s3-cdn)

Expected Behavior

When specified the module will allow passing appropriate config maps to create request header policies in a CloudFront distribution.

Use Case

Users of AWS CloudFront may require setting of request headers for security, caching or other purposes. This has previously required these headers to be set at the origin, or an additional lambda to set these headers. AWS has now enabled this to be set as part of the CloudFront distribution configuration.

Describe Ideal Solution

Additional map(s) similar to the ordered_cache attribute that allows the appropriate config for a CORS, custom or security header policy to be provided.

Alternatives Considered

As described earlier, setting the request header at the origin, or creating an additional lambda. For some use cases both of these approaches may not be possible for various reasons.

Add support for sending custom headers to origin

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

A common use case of CloudFront is to front traffic to an origin. To only allow traffic to a origin through CloudFront, a common method is to specify a header that is injected by CloudFront to all requests going to the origin. This Terraform module should support that feature.

Expected Behavior

A user should be able to specify a number of headers, which are then expressed by a CloudFront distribution.

Use Case

To authorize traffic from CloudFront as a sole source.

Describe Ideal Solution

Only a specific (or several specific) CloudFront distributions can send traffic to a ALB.

Alternatives Considered

Ingress for a ALB can be locked down to a set of CIDRs, but then anybody who can create CloudFront distributions can access the origins. More control is needed.

Cant use cache_policy_id, because another parameters are required

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

When try use cache_policy_id i got error
Error: error creating CloudFront Distribution: InvalidArgument: The parameter ForwardedValues cannot be used when a cache policy is associated to the cache behavior. status code: 400, request id: 9421ef45-20d3-4824-8e69-9b4e9c43af87
But when i try set null in forward parameters i get error:

Error: expected ordered_cache_behavior.0.forwarded_values.0.cookies.0.forward to be one of [all none whitelist], got 

Expected Behavior

CDN will implement with set policy

Steps to Reproduce

Steps to reproduce the behavior:

  1. Configure cdn (https://github.com/cloudposse/terraform-aws-cloudfront-cdn/tree/master/examples/wordpress)
  2. Set cache_policy_id to 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
  3. terraform apply

Screenshots

If applicable, add screenshots or logs to help explain your problem.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: Linux
  • Version Ubuntu 20.04

Additional Context

Add any other context about the problem here.

Bucket cannot have ACLs set with ObjectOwnership's BucketOwnerEnforced setting

Found a bug? Maybe our Slack Community can help.

Slack Community

Describe the Bug

Cannot create a new Cloudfront CDN using this module, the apply command fails with the following error:

Error: creating Amazon S3 (Simple Storage) Bucket (***): InvalidBucketAclWithObjectOwnership: Bucket cannot have ACLs set with ObjectOwnership's BucketOwnerEnforced setting

Expected Behavior

terragrunt apply command should not fail with that error.

Steps to Reproduce

Steps to reproduce the behavior:

  1. Run terragrunt apply with the bare minimum inputs
  2. Receive the error message

Screenshots

If applicable, add screenshots or logs to help explain your problem.

Environment (please complete the following information):

Anything that will help us triage the bug will help. Here are some ideas:

  • OS: Pop! OS
  • Version 22.04 LTS

Additional Context

From my initial research, it looks like AWS changed the default value for new S3 Buckets' ownership controls to BucketOwnerEnforced. This creates a conflict that prevents the Bucket from being created, since BucketOwnerEnforced conflicts with having an ACL defined on the Bucket.

Cannot create custom_origins

Describe the Bug

Cannot create a custom origin behind the default one, because

  1. The given value is not suitable for child module variable "custom_origins" defined at .terraform/modules/cloudfront-cdn/variables.tf:327,1-26: element 0: attribute "s3_origin_config" is required.
    Or when we add s3_origin_config
  2. Error: error updating CloudFront Distribution (E2WW4FISAR8BSH): IllegalUpdate: You must specify either a CustomOrigin or an S3Origin. You cannot specify both.

Expected Behavior

We should be able to add a custom origin accordingly to the documentation

Steps to Reproduce

Add the following block to the main.tf

  custom_origins = [
    {
      domain_name    = "domain.com"
      origin_id      = "custom-origin-staging"
      origin_path    = "/staging"
      custom_headers = []
      custom_origin_config = {
        http_port                = 80
        https_port               = 443
        origin_protocol_policy   = "https-only"
        origin_ssl_protocols     = ["TLSv1", "TLSv1.1", "TLSv1.2"]
        origin_keepalive_timeout = 5
        origin_read_timeout      = 30
      }
    }
  ]

Steps to reproduce the behavior:

  1. Run: terraform plan - get the error about missed s3_origin_config option
  2. Add required option
    s3_origin_config = {
      origin_access_identity = ""
    }
    
  3. Run terraform apply and the the error from CloudFront
    Error: error updating CloudFront Distribution (XXXXXXXXXXXXXX): IllegalUpdate: You must specify either a CustomOrigin or an S3Origin. You cannot specify both.
    

Environment

cloudposse/cloudfront-cdn/aws = 0.22.1
aws = 3.63.0

Additional Context

Maybe something is missing in my configuration, and where we can find a working example with a custom origin?

Thank you!

Dns aliases = false

I've set dns_aliases_enabled to false, but when running terraform plan I get:

  • module.mycdn.module.dns.data.aws_route53_zone.default: 1 error(s) occurred:

  • module.mycdn.module.dns.data.aws_route53_zone.default: data.aws_route53_zone.default: Either name or zone_id must be set

Maybe I've missed something else - but I don't want any zone or zone ID - I don't want anything in Route53.

Bug - web_acl_id is actually web_acl_arn

The parameter web_acl_id is arn of the resource not the id. I had to reverse engineer the same to figure it out :)

Please fix the same, at least in the documentation.

I can fix this in the code and the doco too, shall I raise a PR? :)

Cheers!

Support multiple origins

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

I would like the cdn module to support multiple origins, and behaviours.

Expected Behavior

Should be able to specify multiple origin points (for failover purposes etc), also it should also be possible to point different behaviours to these origins, as you could configure CloudFront to route different types of requests to different origin points types.

Use Case

Currently using this module if we have multiple backends we would need to stand up two module instances because it only supports a single origin. This stops a couple of things, it makes it hard for us to serve static content from say an s3 bucket but dynamic content from an API, all under one distribution. Cached behaviours make it possible to do a path-based routing approach where this is possible but unfortunately by default this module does not support it.

Describe Ideal Solution

Able to specify multiple origin points and associate behaviours with each origin point.

Alternatives Considered

Only alternative is to either write our own module or standup separate distributions.

Additional Context

Managing multiple distributions for one thing seems a bit old school :)

A good working example of this functionality is given here

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Base branch does not exist - skipping

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

Branch main
terraform
main.tf
  • cloudposse/route53-alias/aws 0.13.0
  • cloudposse/s3-log-storage/aws 1.4.2
  • cloudposse/label/null 0.25.0
versions.tf
  • aws >= 4.9.0
  • local >= 1.2
  • hashicorp/terraform >= 1.0
Branch release/v0
terraform
main.tf
  • cloudposse/route53-alias/aws 0.13.0
  • cloudposse/s3-log-storage/aws 1.4.3
  • cloudposse/label/null 0.25.0
versions.tf
  • aws >= 4.27.0
  • local >= 1.2
  • hashicorp/terraform >= 0.13.0

  • Check this box to trigger a request for Renovate to run again on this repository

Create distribution without using Route53

I am trying to use this module to create a Cloudfront distribution with S3 origin.
In my case we use cloudflare for DNS. We don't use Route53.

I am getting an error:
data.aws_route53_zone.default: Either name or zone_id must be set

How can I use this module without using Route53?

We do have a private hosted zone in Route53. Perhaps we can specify the name of that zone.

CloudFront Origin Group

Describe the Feature

CloudFront has a future to create Origin Group which is very usefully for high availability configuration.

Expected Behavior

A way to configure Origin Group, like

  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
    ]
  }

Use Case

Optimizing high availability with CloudFront origin failover

Describe Ideal Solution

Such an option is already supported in the module cloudposse/cloudfront-s3-cdn/aws. Something similar will be a good option.

Thank you!

Feature request: please support applying different cloudfront functions to different behaviors

Have a question? Please checkout our Slack Community or visit our Slack Archive.

Slack Community

Describe the Feature

AWS CloudFront supports using a different cloudfront function for each Behavior. For example, a user may want to have /app go to one s3 bucket and / (default path) go do a different s3 bucket, and the user may want to apply different cloudfront functions for each Origin (which are routed to via Behaviors).

Expected Behavior

By default, apply function to all behaviors (support backwards compatibility), but add a new configuration to apply a function only to a specific Behavior.

Use Case

Users may want to apply different cloudfront functions depending on which Origin is selected. For example one Origin may require appending index.html when a directory is specified, for example S3 Origin, but another may require this is not done, for example when using API Gateway as an Origin.

Describe Ideal Solution

  function_association = [{
    event_type   = "viewer-request"
    function_arn = data.aws_cloudfront_function.viewer_request_homepage.arn
    # New optional attribute:
    target_origin_id = "homepage"
  },
  {
    event_type   = "viewer-request"
    function_arn = data.aws_cloudfront_function.viewer_request_application.arn
    # New optional attribute:
    target_origin_id = "application"
  }
  ]

Alternatives Considered

In the cloudfront function, conditional logic can be used to skip specific handling depending on which Origin would be selected.

Additional Context

If you deploy a cloudfront with functions and multiple origins, then you can select Behavior in the AWS console to see that an AWS user may select different cloudfront functions per Behavior.

how to support multiple parent zones

We are hosting 5 different sites in AWS.
All of them are behind the same ALB.
We want to put CDN in front of all these sites.

When I was creating CDN using your module I specified aliases for all the sites.
aliases = ["int.site1.com","intblog.site2.com","intcksup.site3.com"]

parent_zone = "site1.com"

I noticed that it created DNS records for each of the aliases in one parent domain.
I am trying to figure out a way to create DNS records for site2.com and site3.com parent zones.
Only thing I can come up with is to use Terraform aws_route53_record to create DNS records for site2.com and site3.com. Even if I do this this module will create dns records all three aliases in parent zone for site1.

Is there a way to prevent this module from creating any DNS records for sites specified in aliases?
I am ok if it only creates CDN and expects us to create all the DNS records on our own.

It does not make sense for it to create DNS records like:
intblog.site2.com.site1.com
intcksup.site3.com.site1.com

Thanks

Do not try to create the DNS records when `aliases` is specified.

Describe the Feature

Do not try to create the DNS records when aliases is specified.

Expected Behavior

I should be able to use aliases without creating them using this module.

Use Case

As of now, if you specify aliases, the module tries to find the R53 zone and create the record. In my case, my R53 zone is in a different account which is why fails with the below error

  on .terraform/modules/waf.cdn.dns/main.tf line 1, in data "aws_route53_zone" "default":
   1: data "aws_route53_zone" "default" {

Describe Ideal Solution

I would like to have one of these options

  • Use of aliases without creating the R53 record
  • Option to create an alias by using a different provider (with a different region). This would require to pass two was providers to the module

Alternatives Considered

Create the aliases manually or some script outside of the terraform module

AWS provider v4 breaks module

Describe the Bug

When using the v4.0.0 AWS provider, the module no longer functions correctly:

Error: Unsupported attribute

  on .terraform/modules/logs/main.tf line 30, in resource "aws_s3_bucket" "default":
  30:         for_each = var.enable_glacier_transition ? [1] : []

This object does not have an attribute named "enable_glacier_transition".

Error: Unsupported attribute

  on .terraform/modules/logs/main.tf line 44, in resource "aws_s3_bucket" "default":
  44:         for_each = var.enable_glacier_transition ? [1] : []

This object does not have an attribute named "enable_glacier_transition".
time=2022-02-11T12:18:13Z level=error msg=1 error occurred:
	* exit status 1

Expected Behavior

Module should work!

Steps to Reproduce

Run module as per examples with the v4.0.0 AWS provider

Additional Context

Issue appears to lie with the s3-log-storage module. I have pushed a PR to that module - PR 64 but this module will also need to be updated with new version produced there.

Ability to associate WAF with Cloudfront

I wanted to associate a global AWS WAF ACL with CloudFront. I did not find an option to pass in existing WAF.
Typically I get around this by using null provisioners and executing aws cli.
I took a quick look and I did not see an option to associate a global WAF ACL with CloudFront using CLI.

Add Example Usage

what

  • Add example invocation

why

  • We need this so we can soon enable automated continuous integration testing of module

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.