Skip to main content
Service Catalog Version 0.116.1Last updated in version 0.115.2

Public Static Website

View Source Release Notes

Overview

This service creates a public static website using S3 and CloudFront on AWS. The website can contain static HTML, CSS, JS, and images.

Static S3 WebsiteStatic S3 Website

Features

  • Offload storage and serving of static content (HTML, CSS, JS, images) to a public S3 bucket configured as a website.

  • Create additional buckets to store your website access logs, and your CloudFront access logs.

  • Deploy a CloudFront Distribution in front of the public S3 bucket for your website domain.

  • Optionally:

    • Create a Route 53 entry in IPV4 and IPV6 formats to route requests to your domain name to the public S3 bucket,
    • And associate an existing TLS certificate issued by Amazon’s Certificate Manager (ACM) for your domain.

Learn

Serving static content from S3 rather than from your own app server can significantly reduce the load on your server, allowing it to focus on serving dynamic data. This saves money and makes your website run faster. For even bigger improvements in performance, deploy a CloudFront Content Distribution Network (CDN) in front of the S3 bucket.

note

This repo is a part of the Gruntwork Service Catalog, a collection of reusable, battle-tested, production ready infrastructure code. If you’ve never used the Service Catalog before, make sure to read How to use the Gruntwork Service Catalog!

Core concepts

This module deploys a public website, so the S3 bucket and objects with it are readable by the public. It also is hosted in a Public Hosted Zone in Route 53. You may provide a hosted_zone_id in variables, or you may provide the base_domain_name associated with your Public Hosted Zone in Route 53, optionally along with any tags that must match that zone in base_domain_name_tags. If you do the latter, this module will find the hosted zone id for you.

For more info on why you would use S3 to store static content, why you may want a CDN in front of it, how to access the website, and how to configure SSL, check out the documentation for the s3-static-website and s3-cloudfront modules.

Repo organization

  • modules: the main implementation code for this repo, broken down into multiple standalone, orthogonal submodules.
  • examples: This folder contains working examples of how to use the submodules.
  • test: Automated tests for the modules and examples.

Deploy

Non-production deployment (quick start for learning)

If you just want to try this repo out for experimenting and learning, check out the following resources:

  • examples/for-learning-and-testing folder: The examples/for-learning-and-testing folder contains standalone sample code optimized for learning, experimenting, and testing (but not direct production usage).

Production deployment

If you want to deploy this repo in production, check out the following resources:

Sample Usage

main.tf

# ------------------------------------------------------------------------------------------------------
# DEPLOY GRUNTWORK'S PUBLIC-STATIC-WEBSITE MODULE
# ------------------------------------------------------------------------------------------------------

module "public_static_website" {

source = "git::git@github.com:gruntwork-io/terraform-aws-service-catalog.git//modules/services/public-static-website?ref=v0.116.1"

# ----------------------------------------------------------------------------------------------------
# REQUIRED VARIABLES
# ----------------------------------------------------------------------------------------------------

# The domain name for which an ACM cert has been issued (e.g. *.foo.com). Only
# used if var.create_route53_entry is true. Set to blank otherwise.
acm_certificate_domain_name = <string>

# The name of the website and the S3 bucket to create (e.g. static.foo.com).
website_domain_name = <string>

# ----------------------------------------------------------------------------------------------------
# OPTIONAL VARIABLES
# ----------------------------------------------------------------------------------------------------

# The domain name associated with a hosted zone in Route 53. Usually the base
# domain name of var.website_domain_name (e.g. foo.com). This is used to find
# the hosted zone that will be used for the CloudFront distribution. If
# var.create_route53_entry is true, one of var.base_domain_name or
# var.hosted_zone_id must be provided.
base_domain_name = null

# The tags associated with var.base_domain_name. If there are multiple hosted
# zones for the same var.base_domain_name, this will help filter the hosted
# zones so that the correct hosted zone is found.
base_domain_name_tags = {}

# A configuration for CORS on the S3 bucket. Default value comes from AWS. Can
# override for custom CORS by passing the object structure define in the
# documentation
# https://www.terraform.io/docs/providers/aws/r/s3_bucket.html#using-cors.
cors_rule = []

# If set to true, create a DNS A Record in Route 53. If
# var.create_route53_entry is true, one of var.base_domain_name or
# var.hosted_zone_id must be provided.
create_route53_entry = true

# Map of custom headers.
custom_headers = null

# A map of custom tags to apply to the S3 bucket containing the website and
# the CloudFront distribution created for it. The key is the tag name and the
# value is the tag value.
custom_tags = {}

# A list of existing CloudFront functions to associate with the default cached
# behavior. CloudFront functions are lightweight alternatives to Lambda for
# high-scale, latency sensitive CDN customizations.
default_function_associations = []

# A list of existing Lambda@Edge functions to associate with CloudFront.
# Lambda version must be a published version and cannot be `$LATEST` (See
# https://www.terraform.io/docs/providers/aws/r/cloudfront_distribution.html#lambda_function_association
# for available options).
default_lambda_associations = []

# The default amount of time, in seconds, that an object is in a CloudFront
# cache before CloudFront forwards another request in the absence of an
# 'Cache-Control max-age' or 'Expires' header.
default_ttl = 30

# Option to disable cloudfront log delivery to s3. This is required in regions
# where cloudfront cannot deliver logs to s3, see
# https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#access-logs-choosing-s3-bucket
disable_cloudfront_logging = false

# If set to true, a CloudFront function to implement default directory index
# (looking up index.html in an S3 directory when path ends in /) is deployed.
# Only relevant when var.restrict_bucket_access_to_cloudfront is set to true.
enable_default_directory_index_function = false

# Set to true to enable versioning. This means the bucket will retain all old
# versions of all files. This is useful for backup purposes (e.g. you can
# rollback to an older version), but it may mean your bucket uses more
# storage.
enable_versioning = true

# The path to the error document in the S3 bucket (e.g. error.html).
error_document = "error.html"

# The error responses you want CloudFront to return to the viewer.
error_responses = {"404":{"error_caching_min_ttl":0,"response_code":404,"response_page_path":"404.html"},"500":{"error_caching_min_ttl":0,"response_code":500,"response_page_path":"500.html"}}

# If set to true, this will force the deletion of the website, redirect, and
# access log S3 buckets when you run terraform destroy, even if there is still
# content in those buckets. This is only meant for testing and should not be
# used in production.
force_destroy = false

# The headers you want CloudFront to forward to the origin. Set to * to
# forward all headers.
forward_headers = []

# The ISO 3166-1-alpha-2 codes for which you want CloudFront either to
# distribute your content (if var.geo_restriction_type is whitelist) or not
# distribute your content (if var.geo_restriction_type is blacklist).
geo_locations_list = []

# The method that you want to use to restrict distribution of your content by
# country: none, whitelist, or blacklist.
geo_restriction_type = "none"

# The ID of the Route 53 Hosted Zone in which to create the DNS A Records
# specified in var.website_domain_name. If var.create_route53_entry is true,
# one of var.base_domain_name or var.hosted_zone_id must be provided.
hosted_zone_id = null

# The path to the index document in the S3 bucket (e.g. index.html).
index_document = "index.html"

# The maximum amount of time, in seconds, that an object is in a CloudFront
# cache before CloudFront forwards another request to your origin to determine
# whether the object has been updated. Only effective in the presence of
# 'Cache-Control max-age', 'Cache-Control s-maxage', and 'Expires' headers.
max_ttl = 60

# The minimum amount of time that you want objects to stay in CloudFront
# caches before CloudFront queries your origin to see whether the object has
# been updated.
min_ttl = 0

# The minimum version of the SSL protocol that you want CloudFront to use for
# HTTPS connections. Refer to
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_distribution#minimum_protocol_version
# for possible values.
minimum_protocol_version = "TLSv1"

# If set to true, the S3 bucket will only be accessible via CloudFront, and
# not directly. NOTE: this is only known to work if the S3 Bucket is in
# us-east-1.
restrict_bucket_access_to_cloudfront = false

# A map describing the routing_rule for the aws_s3_website_configuration
# resource. Describes redirect behavior and conditions when redirects are
# applied. Conflicts with routing_rules. Use routing_rules if rules contain
# empty String values.
routing_rule = {}

# A json string array containing routing rules for the
# aws_s3_website_configuration resource. Describes redirect behavior and
# conditions when redirects are applied. Conflicts with routing_rule. Use this
# when routing rules contain empty String values.
routing_rules = null

# By default, the s3 bucket hosting the website is named after the domain
# name. Use this configuration to override it with this value instead.
s3_bucket_override_bucket_name = null

# The policy directives and their values that CloudFront includes as values
# for the Content-Security-Policy HTTP response header. When null, the header
# is omitted.
security_header_content_security_policy = "default-src 'self'; base-uri 'self'; block-all-mixed-content; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests"

# Determines whether CloudFront includes the X-Content-Type-Options HTTP
# response header with its value set to nosniff.
security_header_enable_nosniff_content_type_options = true

# Determines whether CloudFront includes the X-Frame-Options HTTP response
# header and the header’s value. When null, the header is omitted.
security_header_frame_option = "SAMEORIGIN"

# Determines whether CloudFront includes the Strict-Transport-Security HTTP
# response header and the header’s value. When null, the header is omitted.
security_header_hsts = {"include_subdomains":true,"max_age":15552000,"preload":false}

# Determines whether CloudFront includes the Referrer-Policy HTTP response
# header and the header’s value. When null, the header is omitted.
security_header_referrer_policy = "no-referrer"

# Determine whether CloudFront includes the X-Xss-Protection HTTP response
# header and the header’s value. When null, the header is omitted.
security_header_xss_protection = {"mode_block":false,"protection":false,"report_uri":null}

# In older AWS accounts, you must set this variable to true to use the ARN of
# the CloudFront log delivery AWS account in the access log bucket policy. In
# newer AWS accounts, you must set this variable to false to use the
# CanonicalUser ID of the CloudFront log delivery account. If you pick the
# wrong value, you'll get a perpetual diff on the IAM policy. See
# https://github.com/terraform-providers/terraform-provider-aws/issues/10158
# for context.
use_cloudfront_arn_for_bucket_policy = false

# Use this element to specify the protocol that users can use to access the
# files in the origin specified by TargetOriginId when a request matches the
# path pattern in PathPattern. One of allow-all, https-only, or
# redirect-to-https.
viewer_protocol_policy = "allow-all"

# If you're using AWS WAF to filter CloudFront requests, the Id of the AWS WAF
# web ACL that is associated with the distribution. Refer to
# https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_distribution#web_acl_id
# for more details.
web_acl_id = null

}


Reference

Required

The domain name for which an ACM cert has been issued (e.g. *.foo.com). Only used if create_route53_entry is true. Set to blank otherwise.

website_domain_namestringrequired

The name of the website and the S3 bucket to create (e.g. static.foo.com).

Optional

base_domain_namestringoptional

The domain name associated with a hosted zone in Route 53. Usually the base domain name of website_domain_name (e.g. foo.com). This is used to find the hosted zone that will be used for the CloudFront distribution. If create_route53_entry is true, one of base_domain_name or hosted_zone_id must be provided.

null
base_domain_name_tagsmap(any)optional

The tags associated with base_domain_name. If there are multiple hosted zones for the same base_domain_name, this will help filter the hosted zones so that the correct hosted zone is found.

Any types represent complex values of variable type. For details, please consult `variables.tf` in the source repo.
{}
cors_ruleanyoptional

A configuration for CORS on the S3 bucket. Default value comes from AWS. Can override for custom CORS by passing the object structure define in the documentation https://www.terraform.io/docs/providers/aws/r/s3_bucket.html#using-cors.

Any types represent complex values of variable type. For details, please consult `variables.tf` in the source repo.
[]

If set to true, create a DNS A Record in Route 53. If create_route53_entry is true, one of base_domain_name or hosted_zone_id must be provided.

true
custom_headersmap(string)optional

Map of custom headers.

null
custom_tagsmap(string)optional

A map of custom tags to apply to the S3 bucket containing the website and the CloudFront distribution created for it. The key is the tag name and the value is the tag value.

{}
default_function_associationslist(object(…))optional

A list of existing CloudFront functions to associate with the default cached behavior. CloudFront functions are lightweight alternatives to Lambda for high-scale, latency sensitive CDN customizations.

list(object({
event_type = string
function_arn = string
}))
[]
default_lambda_associationslist(object(…))optional

A list of existing Lambda@Edge functions to associate with CloudFront. Lambda version must be a published version and cannot be $LATEST (See https://www.terraform.io/docs/providers/aws/r/cloudfront_distribution.html#lambda_function_association for available options).

list(object({
event_type = string
lambda_arn = string
include_body = bool
}))
[]
default_ttlnumberoptional

The default amount of time, in seconds, that an object is in a CloudFront cache before CloudFront forwards another request in the absence of an 'Cache-Control max-age' or 'Expires' header.

30

Option to disable cloudfront log delivery to s3. This is required in regions where cloudfront cannot deliver logs to s3, see https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#access-logs-choosing-s3-bucket

false

If set to true, a CloudFront function to implement default directory index (looking up index.html in an S3 directory when path ends in /) is deployed. Only relevant when restrict_bucket_access_to_cloudfront is set to true.

false
enable_versioningbooloptional

Set to true to enable versioning. This means the bucket will retain all old versions of all files. This is useful for backup purposes (e.g. you can rollback to an older version), but it may mean your bucket uses more storage.

true
error_documentstringoptional

The path to the error document in the S3 bucket (e.g. error.html).

"error.html"
error_responsesmap(object(…))optional

The error responses you want CloudFront to return to the viewer.

map(object({
response_code = number
response_page_path = string
error_caching_min_ttl = number
}))
{
404 = {
error_caching_min_ttl = 0,
response_code = 404,
response_page_path = "404.html"
},
500 = {
error_caching_min_ttl = 0,
response_code = 500,
response_page_path = "500.html"
}
}
Example
   default = {
404 = {
response_code = 404
response_page_path = "404.html"
error_caching_min_ttl = 0
}
}

force_destroybooloptional

If set to true, this will force the deletion of the website, redirect, and access log S3 buckets when you run terraform destroy, even if there is still content in those buckets. This is only meant for testing and should not be used in production.

false
forward_headerslist(string)optional

The headers you want CloudFront to forward to the origin. Set to * to forward all headers.

[]
geo_locations_listlist(string)optional

The ISO 3166-1-alpha-2 codes for which you want CloudFront either to distribute your content (if geo_restriction_type is whitelist) or not distribute your content (if geo_restriction_type is blacklist).

[]
geo_restriction_typestringoptional

The method that you want to use to restrict distribution of your content by country: none, whitelist, or blacklist.

"none"
hosted_zone_idstringoptional

The ID of the Route 53 Hosted Zone in which to create the DNS A Records specified in website_domain_name. If create_route53_entry is true, one of base_domain_name or hosted_zone_id must be provided.

null
index_documentstringoptional

The path to the index document in the S3 bucket (e.g. index.html).

"index.html"
max_ttlnumberoptional

The maximum amount of time, in seconds, that an object is in a CloudFront cache before CloudFront forwards another request to your origin to determine whether the object has been updated. Only effective in the presence of 'Cache-Control max-age', 'Cache-Control s-maxage', and 'Expires' headers.

60
min_ttlnumberoptional

The minimum amount of time that you want objects to stay in CloudFront caches before CloudFront queries your origin to see whether the object has been updated.

0

The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. Refer to https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_distribution#minimum_protocol_version for possible values.

"TLSv1"

If set to true, the S3 bucket will only be accessible via CloudFront, and not directly. NOTE: this is only known to work if the S3 Bucket is in us-east-1.

false
routing_ruleanyoptional

A map describing the routing_rule for the aws_s3_website_configuration resource. Describes redirect behavior and conditions when redirects are applied. Conflicts with routing_rules. Use routing_rules if rules contain empty String values.

Any types represent complex values of variable type. For details, please consult `variables.tf` in the source repo.
{}
routing_rulesstringoptional

A json string array containing routing rules for the aws_s3_website_configuration resource. Describes redirect behavior and conditions when redirects are applied. Conflicts with routing_rule. Use this when routing rules contain empty String values.

null

By default, the s3 bucket hosting the website is named after the domain name. Use this configuration to override it with this value instead.

null

The policy directives and their values that CloudFront includes as values for the Content-Security-Policy HTTP response header. When null, the header is omitted.

"default-src 'self'; base-uri 'self'; block-all-mixed-content; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests"

Determines whether CloudFront includes the X-Content-Type-Options HTTP response header with its value set to nosniff.

true

Determines whether CloudFront includes the X-Frame-Options HTTP response header and the header’s value. When null, the header is omitted.

"SAMEORIGIN"
security_header_hstsobject(…)optional

Determines whether CloudFront includes the Strict-Transport-Security HTTP response header and the header’s value. When null, the header is omitted.

object({
# The number of seconds browsers should remember to prefer HTTPS.
max_age = number
# Whether to include subdomains in the policy.
include_subdomains = bool
# Whether to add the HSTS policy to browsers.
preload = bool
})
{
include_subdomains = true,
max_age = 15552000,
preload = false
}

Determines whether CloudFront includes the Referrer-Policy HTTP response header and the header’s value. When null, the header is omitted.

"no-referrer"

Determine whether CloudFront includes the X-Xss-Protection HTTP response header and the header’s value. When null, the header is omitted.

object({
# A Boolean value that determines whether CloudFront includes the mode=block directive in the X-XSS-Protection header.
mode_block = bool
# A Boolean value that determines the value of the X-Xss-Protection HTTP response header (true = 1, false = 0).
protection = bool
# A reporting URI, which CloudFront uses as the value of the report directive in the X-XSS-Protection header. You cannot specify a report_uri when mode_block is true.
report_uri = string
})
{
mode_block = false,
protection = false,
report_uri = null
}

In older AWS accounts, you must set this variable to true to use the ARN of the CloudFront log delivery AWS account in the access log bucket policy. In newer AWS accounts, you must set this variable to false to use the CanonicalUser ID of the CloudFront log delivery account. If you pick the wrong value, you'll get a perpetual diff on the IAM policy. See https://github.com/terraform-providers/terraform-provider-aws/issues/10158 for context.

false

Use this element to specify the protocol that users can use to access the files in the origin specified by TargetOriginId when a request matches the path pattern in PathPattern. One of allow-all, https-only, or redirect-to-https.

"allow-all"
web_acl_idstringoptional

If you're using AWS WAF to filter CloudFront requests, the Id of the AWS WAF web ACL that is associated with the distribution. Refer to https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_distribution#web_acl_id for more details.

null