If you want to skip all of the fun the repo with the code we are using is located here. Also, before you get started here go check out my article on creating an S3 website bucket module. This article will be building on the groundwork set there and will assume you have an S3 bucket module.

S3 Bucket Code

For this article, I am going to assume that you already have an S3 website created and just want to get it deployed to Cloudfront using Terraform. If that happens to not be the case here is the code we are working with.

Main.tf

resource "aws_s3_bucket" "prod_website" {  
  bucket_prefix = var.bucket_prefix  
  acl    = "public-read"     website {    
    index_document = "index.html"    
    error_document = "error.html"   

  }
}
resource "aws_s3_bucket_policy" "prod_website" {  
  bucket = aws_s3_bucket.prod_website.id   policy = <<POLICY
{    
    "Version": "2012-10-17",    
    "Statement": [        
      {            
          "Sid": "PublicReadGetObject",            
          "Effect": "Allow",            
          "Principal": "*",            
          "Action": [                
             "s3:GetObject"            
          ],            
          "Resource": [
             "arn:aws:s3:::${aws_s3_bucket.prod_website.id}/*"            
          ]        
      }    
    ]
}
POLICY
}

Variables.tf

variable "bucket_prefix" {  
  type        = string  
  description = "Name of the s3 bucket to be created."
} 
variable "region" {  
  type        = string  
  default     = "us-east-1"  
  description = "Name of the s3 bucket to be created."
}

Outputs.tf

output "s3_bucket_id" {
  value = aws_s3_bucket.prod_website.id
}

Use these files as the basis for your code. We will just be updating them with our Cloudfront code.

#infrastructure-as-code #terraform-modules #aws #terraform #hashicorp

Using Terraform to Deploy Your S3 Website Using Cloudfront
2.35 GEEK