Skip to content

terraform-aws-modules/terraform-aws-cloudfront

AWS CloudFront Terraform module

Terraform module which creates AWS CloudFront resources with all (or almost all) features provided by Terraform AWS provider.

Usage

CloudFront distribution with versioning enabled

module "cdn" {
  source = "terraform-aws-modules/cloudfront/aws"

  aliases = ["cdn.example.com"]
  comment = "My awesome CloudFront"

  origin_access_control = {
    s3_oac = {
      description      = "CloudFront access to S3"
      origin_type      = "s3"
      signing_behavior = "always"
      signing_protocol = "sigv4"
    }
  }

  logging_config = {
    bucket = "logs-my-cdn.s3.amazonaws.com"
  }

  origin = {
    something = {
      domain_name = "something.example.com"
      custom_origin_config = {
        http_port              = 80
        https_port             = 443
        origin_protocol_policy = "match-viewer"
        origin_ssl_protocols   = ["TLSv1.2"]
      }
    }
  }

  default_cache_behavior = {
    target_origin_id       = "something"
    viewer_protocol_policy = "allow-all"

    allowed_methods = ["GET", "HEAD", "OPTIONS"]
    cached_methods  = ["GET", "HEAD"]
    compress        = true
    query_string    = true
  }

  ordered_cache_behavior = [
    {
      path_pattern           = "/static/*"
      target_origin_id       = "s3"
      viewer_protocol_policy = "redirect-to-https"

      allowed_methods = ["GET", "HEAD", "OPTIONS"]
      cached_methods  = ["GET", "HEAD"]
      compress        = true
      query_string    = true
    }
  ]

  viewer_certificate = {
    acm_certificate_arn = "arn:aws:acm:us-east-1:135367859851:certificate/1032b155-22da-4ae0-9f69-e206f825458b"
    ssl_support_method  = "sni-only"
  }
}

CloudFront distribution with CloudFront Functions

module "cdn" {
  source = "terraform-aws-modules/cloudfront/aws"

  aliases = ["cdn.example.com"]
  comment = "CloudFront with Functions"

  origin_access_control = {
    s3 = {
      description      = "CloudFront access to S3"
      origin_type      = "s3"
      signing_behavior = "always"
      signing_protocol = "sigv4"
    }
  }

  # Enable CloudFront Functions
  cloudfront_functions = {
    viewer-request-function = {
      runtime = "cloudfront-js-2.0"
      comment = "Function to add security headers and modify requests"
      code    = file("${path.module}/functions/viewer-request.js")
      publish = true
    }

    viewer-response-function = {
      runtime = "cloudfront-js-2.0"
      comment = "Function to add security response headers"
      code    = file("${path.module}/functions/viewer-response.js")
      publish = true
      # Optional: Associate with CloudFront KeyValueStore
      key_value_store_associations = ["arn:aws:cloudfront::123456789012:key-value-store/example-store"]
    }
  }

  origin = {
    s3_bucket = {
      domain_name = "my-bucket.s3.amazonaws.com"
    }
  }

  default_cache_behavior = {
    target_origin_id       = "s3_bucket"
    viewer_protocol_policy = "redirect-to-https"

    allowed_methods = ["GET", "HEAD", "OPTIONS"]
    cached_methods  = ["GET", "HEAD"]
    compress        = true
    query_string    = true

    # Associate CloudFront Functions with cache behavior
    # Option 1: Direct ARN reference (recommended for external functions)
    # function_association = {
    #   viewer-request = {
    #     function_arn = aws_cloudfront_function.external.arn
    #   }
    # }

    # Option 2: Dynamic reference to module-managed functions by key/name
    function_association = {
      viewer-request = {
        function_key = "viewer-request-function"
      }
      viewer-response = {
        function_key = "viewer-response-function"
      }
    }
  }

  viewer_certificate = {
    acm_certificate_arn = "arn:aws:acm:us-east-1:135367859851:certificate/1032b155-22da-4ae0-9f69-e206f825458b"
    ssl_support_method  = "sni-only"
  }
}

Examples

  • Complete - Complete example which creates AWS CloudFront distribution and integrates it with other terraform-aws-modules to create additional resources: S3 buckets, Lambda Functions, CloudFront Functions, VPC Origins, ACM Certificate, Route53 Records.

Requirements

Name Version
terraform >= 1.5.7
aws >= 6.20

Providers

Name Version
aws >= 6.20

Modules

No modules.

Resources

Name Type
aws_cloudfront_distribution.this resource
aws_cloudfront_function.this resource
aws_cloudfront_monitoring_subscription.this resource
aws_cloudfront_origin_access_control.this resource
aws_cloudfront_response_headers_policy.this resource
aws_cloudfront_vpc_origin.this resource
aws_cloudfront_cache_policy.this data source
aws_cloudfront_origin_request_policy.this data source
aws_cloudfront_response_headers_policy.this data source

Inputs

Name Description Type Default Required
aliases Extra CNAMEs (alternate domain names), if any, for this distribution list(string) null no
anycast_ip_list_id ID of the Anycast static IP list that is associated with the distribution string null no
cloudfront_functions Map of CloudFront Function configurations. Key is used as default function name if 'name' not specified
map(object({
name = optional(string)
runtime = optional(string, "cloudfront-js-2.0")
comment = optional(string)
publish = optional(bool)
code = string
key_value_store_associations = optional(list(string))
}))
null no
comment Any comments you want to include about the distribution string null no
continuous_deployment_policy_id Identifier of a continuous deployment policy. This argument should only be set on a production distribution string null no
create Controls if resources should be created (affects nearly all resources) bool true no
create_monitoring_subscription If enabled, the resource for monitoring subscription will created bool false no
custom_error_response One or more custom error response elements
list(object({
error_caching_min_ttl = optional(number)
error_code = number
response_code = optional(number)
response_page_path = optional(string)
}))
null no
default_cache_behavior The default cache behavior for this distribution
object({
allowed_methods = optional(list(string), ["GET", "HEAD", "OPTIONS"])
cache_policy_id = optional(string)
cache_policy_name = optional(string)
cached_methods = optional(list(string), ["GET", "HEAD"])
compress = optional(bool, true)
default_ttl = optional(number)
field_level_encryption_id = optional(string)
forwarded_values = optional(object({
cookies = object({
forward = optional(string, "none")
whitelisted_names = optional(list(string))
})
headers = optional(list(string))
query_string = optional(bool, false)
query_string_cache_keys = optional(list(string))
}),
{
cookies = {
forward = "none"
}
query_string = false
}
)
function_association = optional(map(object({
event_type = optional(string)
function_arn = optional(string)
function_key = optional(string)
})))
grpc_config = optional(object({
enabled = optional(bool)
}))
lambda_function_association = optional(map(object({
event_type = optional(string)
include_body = optional(bool)
lambda_arn = string
})))
max_ttl = optional(number)
min_ttl = optional(number)
origin_request_policy_id = optional(string)
origin_request_policy_name = optional(string)
realtime_log_config_arn = optional(string)
response_headers_policy_id = optional(string)
response_headers_policy_name = optional(string)
smooth_streaming = optional(bool)
target_origin_id = string
trusted_key_groups = optional(list(string))
trusted_signers = optional(list(string))
viewer_protocol_policy = optional(string, "https-only")
})
n/a yes
default_root_object The object that you want CloudFront to return (for example, index.html) when an end user requests the root URL string null no
enabled Whether the distribution is enabled to accept end user requests for content bool true no
http_version The maximum HTTP version to support on the distribution. Allowed values are http1.1, http2, http2and3, and http3. The default is http2 string "http2" no
is_ipv6_enabled Whether the IPv6 is enabled for the distribution bool true no
logging_config The logging configuration that controls how logs are written to your distribution (maximum one)
object({
bucket = optional(string)
include_cookies = optional(bool)
prefix = optional(string)
})
null no
ordered_cache_behavior 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
list(object({
allowed_methods = optional(list(string), ["GET", "HEAD", "OPTIONS"])
cached_methods = optional(list(string), ["GET", "HEAD"])
cache_policy_id = optional(string)
cache_policy_name = optional(string)
compress = optional(bool, true)
default_ttl = optional(number)
field_level_encryption_id = optional(string)
forwarded_values = optional(object({
cookies = object({
forward = optional(string, "none")
whitelisted_names = optional(list(string))
})
headers = optional(list(string))
query_string = optional(bool, false)
query_string_cache_keys = optional(list(string))
}),
{
cookies = {
forward = "none"
}
query_string = false
}
)
function_association = optional(map(object({
event_type = optional(string)
function_arn = optional(string)
function_key = optional(string)
})))
grpc_config = optional(object({
enabled = optional(bool)
}))
lambda_function_association = optional(map(object({
event_type = optional(string)
include_body = optional(bool)
lambda_arn = string
})))
max_ttl = optional(number)
min_ttl = optional(number)
origin_request_policy_id = optional(string)
origin_request_policy_name = optional(string)
path_pattern = string
realtime_log_config_arn = optional(string)
response_headers_policy_id = optional(string)
response_headers_policy_name = optional(string)
smooth_streaming = optional(bool)
target_origin_id = string
trusted_key_groups = optional(list(string))
trusted_signers = optional(list(string))
viewer_protocol_policy = string
}))
null no
origin One or more origins for this distribution (multiples allowed)
map(object({
connection_attempts = optional(number)
connection_timeout = optional(number)
custom_header = optional(map(string))
custom_origin_config = optional(object({
http_port = number
https_port = number
ip_address_type = optional(string)
origin_keepalive_timeout = optional(number)
origin_read_timeout = optional(number)
origin_protocol_policy = string
origin_ssl_protocols = optional(list(string), ["TLSv1.2"])
}))
domain_name = string
origin_access_control_key = optional(string)
origin_access_control_id = optional(string)
origin_id = optional(string)
origin_path = optional(string)
origin_shield = optional(object({
enabled = bool
origin_shield_region = optional(string)
}))
response_completion_timeout = optional(number)
vpc_origin_config = optional(object({
origin_keepalive_timeout = optional(number)
origin_read_timeout = optional(number)
vpc_origin_id = optional(string)
vpc_origin_key = optional(string)
}))
}))
{} no
origin_access_control Map of CloudFront origin access control
map(object({
description = optional(string)
name = optional(string)
origin_type = string
signing_behavior = string
signing_protocol = string
}))
{
"s3": {
"origin_type": "s3",
"signing_behavior": "always",
"signing_protocol": "sigv4"
}
}
no
origin_group One or more origin_group for this distribution (multiples allowed)
map(object({
failover_criteria = object({
status_codes = list(number)
})
member = list(object({
origin_id = string
}))
origin_id = optional(string)
}))
null no
price_class The price class for this distribution. One of PriceClass_All, PriceClass_200, PriceClass_100 string null no
realtime_metrics_subscription_status A flag that indicates whether additional CloudWatch metrics are enabled for a given CloudFront distribution. Valid values are Enabled and Disabled string "Enabled" no
response_headers_policies Map of CloudFront response headers policies with their configurations
map(object({
name = optional(string)
comment = optional(string)
cors_config = optional(object({
access_control_allow_credentials = bool
origin_override = bool
access_control_allow_headers = object({
items = list(string)
})
access_control_allow_methods = object({
items = list(string)
})
access_control_allow_origins = object({
items = list(string)
})
access_control_expose_headers = optional(object({
items = list(string)
}))
access_control_max_age_sec = optional(number)
}))
custom_headers_config = optional(object({
items = list(object({
header = string
override = bool
value = string
}))
}))
remove_headers_config = optional(object({
items = list(object({
header = string
}))
}))
security_headers_config = optional(object({
content_security_policy = optional(object({
content_security_policy = string
override = bool
}))
content_type_options = optional(object({
override = bool
}))
frame_options = optional(object({
frame_option = string
override = bool
}))
referrer_policy = optional(object({
referrer_policy = string
override = bool
}))
strict_transport_security = optional(object({
access_control_max_age_sec = number
override = bool
include_subdomains = optional(bool)
preload = optional(bool)
}))
xss_protection = optional(object({
mode_block = bool
override = bool
protection = bool
report_uri = optional(string)
}))
}))
server_timing_headers_config = optional(object({
enabled = bool
sampling_rate = number
}))
}))
null no
restrictions The restrictions configuration for this distribution
object({
geo_restriction = object({
locations = optional(list(string))
restriction_type = optional(string, "none")
})
})
{
"geo_restriction": {
"restriction_type": "none"
}
}
no
retain_on_delete Disables the distribution instead of deleting it when destroying the resource through Terraform. If this is set, the distribution needs to be deleted manually afterwards bool null no
staging Whether the distribution is a staging distribution bool null no
tags A map of tags to add to all resources map(string) {} no
viewer_certificate The SSL configuration for this distribution
object({
acm_certificate_arn = optional(string)
cloudfront_default_certificate = optional(bool)
iam_certificate_id = optional(string)
minimum_protocol_version = optional(string, "TLSv1.2_2025")
ssl_support_method = optional(string)
})
{} no
vpc_origin Map of CloudFront VPC origins
map(object({
arn = string
http_port = number
https_port = number
name = optional(string)
origin_protocol_policy = string
origin_ssl_protocols = object({
items = optional(list(string), ["TLSv1.2"])
quantity = optional(number, 1)
})
timeouts = optional(object({
create = optional(string)
update = optional(string)
delete = optional(string)
}))
tags = optional(map(string), {})
}))
null no
wait_for_deployment If enabled, the resource will wait for the distribution status to change from InProgress to Deployed. Setting this to false will skip the process bool null no
web_acl_id If you're using AWS WAF to filter CloudFront requests, the Id of the AWS WAF web ACL that is associated with the distribution. The WAF Web ACL must exist in the WAF Global (CloudFront) region and the credentials configuring this argument must have waf:GetWebACL permissions assigned. If using WAFv2, provide the ARN of the web ACL string null no

Outputs

Name Description
cloudfront_distribution_arn The ARN (Amazon Resource Name) for the distribution.
cloudfront_distribution_caller_reference Internal value used by CloudFront to allow future updates to the distribution configuration.
cloudfront_distribution_domain_name The domain name corresponding to the distribution.
cloudfront_distribution_etag The current version of the distribution's information.
cloudfront_distribution_hosted_zone_id The CloudFront Route 53 zone ID that can be used to route an Alias Resource Record Set to.
cloudfront_distribution_id The identifier for the distribution.
cloudfront_distribution_in_progress_validation_batches The number of invalidation batches currently in progress.
cloudfront_distribution_last_modified_time The date and time the distribution was last modified.
cloudfront_distribution_status The current status of the distribution. Deployed if the distribution's information is fully propagated throughout the Amazon CloudFront system.
cloudfront_distribution_trusted_signers List of nested attributes for active trusted signers, if the distribution is set up to serve private content with signed URLs
cloudfront_functions The CloudFront Functions created
cloudfront_monitoring_subscription_id The ID of the CloudFront monitoring subscription, which corresponds to the distribution_id.
cloudfront_origin_access_controls The origin access controls created
cloudfront_response_headers_policies The response headers policies created
cloudfront_vpc_origins The IDS of the VPC origin created

Authors

Module is maintained by Anton Babenko with help from these awesome contributors:

License

Apache 2 Licensed. See LICENSE for full details.

About

Terraform module to create AWS CloudFront resources πŸ‡ΊπŸ‡¦

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

  •  

Packages

No packages published

Contributors 38

Languages