Terraform module | Static site with S3 and Cloudfront

Anil Augustine Chalissery
2 min readMay 6, 2022

In this post lets see how to create a s3-cloudfront website with terraform module.

We assume you have an ssl certificate in AWS certificate manager in issued state and also have access to DNS for pointing the site

With this code you can create an s3 bucket and cloudfront distribution. Once distribution is created you may add cloudfront record in dns. You will also need to add files in s3 and might need to create an invalidation with “/*” for quick results.

file structure

Here we have two directory in root directory. s3-cloudfront directory is the module code for creating s3 and cloudfront, where as env folder consits of call to the modules. This env directory is not mandatory, but i would suggest this way so that we can separate parallel envs in folders.

So now lets start with s3-cloudfront directory. This directory consists of two files main.tf and variables.tf.

In this main.tf we creates an S3 bucket and attaches a bucket policy with GetObject access to cloudfront orgin access identity. Then a cloudfront distribution is created with the ACM arn and in the domain provided by us. Now let see variables.tf

In variables.tf file we requests for 5 variables.

  • variable “environment” {} : This variable stands for the Env of resource and is appended with s3 bucket name.
  • variable “name” {} : This is name of the resources
  • variable “acm” {} : arn of AWS Certificate manager is provided here. Make sure this certificate is in “issued” status
  • variable “domain” {} : This will be the custom domain name of our distribution.
  • variable “root_object” {} : usually index.html

Now lets see whats in env/prod directory. Here we have the parent module where we call the child modules.

In this main.tf we provide variable values and the location of module directory.

Now lets checkout the main.tf and provider.tf in root directory.

so that’s it for creating a s3 bucket and distribution. In case we are planning to create a new env you may create a new folder in env directory and add main.tf with appropriate changes, also don’t forget to add this module in root main.tf.

Once resources is created you can add site files in s3 bucket and create an invalidation with “/*” for faster clearing of cache.

Hope this post helped you in creating a static site with s3 bucket and cloudfront using Terraform module. Do comment for any queries and applaud if this post helped, also follow for more.

--

--