Hosting a Static Website on Amazon S3 with Terraform: A Step-by-Step Guide
Published: 2024-06-27 04:30:02

**Introduction**
In the world of web development, static websites offer a straightforward and efficient way to present content without the complexities of server-side processing. Amazon S3 provides a robust platform for hosting these static websites, ensuring high availability and scalability. To further streamline the deployment process, Terraform, an Infrastructure as Code (IaC) tool, can be used to automate the creation and management of your AWS resources.

This guide will walk you through the process of hosting a static website on Amazon S3 using Terraform, leveraging a modular file structure for clarity and ease of management. By the end of this tutorial, you'll have a fully functional static website hosted on Amazon S3, managed entirely through Terraform.

**Prerequisites**
Before we dive into the steps, let's ensure you have the following prerequisites in place:

1. AWS Account: If you don't have one, sign up for an AWS account.
2. Terraform Installed: Download and install Terraform from the official website.
3. AWS CLI Installed: Install the AWS CLI by following the instructions here.
4. AWS Credentials Configured: Configure your AWS CLI with your credentials by running aws configure.

**Step-1:** Create the Directory Structure
First, let's create a directory for our Terraform project and navigate into it.

```
mkdir my-static-website
cd my-static-website
```
**Step-2:** Define your Terraform Configuration

Create a file named terraform.tf and define your provider configuration. This configuration sets up the Terraform to use the AWS provider, specifying your AWS profile and region



```
# Terraform
terraform {
  required_version = "1.8.5"
  required_providers {
    aws = {
        source = "hashicorp/aws"
        version = "5.40.0"
    }
  }
}

#Provider
provider "aws" {
  profile = "default"
  region = "us-east-1"
}
```
**Step-3:** Create the S3 bucket
Create a file named bucket.tf to define your S3 bucket and its configuration. This defines a S3 bucket and uploads an index.html file to it.

```
# Create S3 Bucket
resource "aws_s3_bucket" "terraform-demo-1808" {
  bucket = "terraform-demo-1808"
}

# Upload file to S3
resource "aws_s3_object" "terraform_index" {
  bucket = aws_s3_bucket.terraform-demo-1808.id
  key = "index.html"
  source = "index.html"
  content_type = "text/html"
  etag = filemd5("index.html")
}

# S3 Web hosting
resource "aws_s3_bucket_website_configuration" "terraform_hosting" {
  bucket = aws_s3_bucket.terraform-demo-1808.id

  index_document {
    suffix = "index.html"
  }
}
```
**Step-4:** Set up the bucket policies 
Create a file named policy.tf to define your S3 bucket policies to allow public access. This block temporarily disables S3’s default Block Public Access settings for this specific bucket.

```
# S3 public access
resource "aws_s3_bucket_public_access_block" "terraform-demo" {
    bucket = aws_s3_bucket.terraform-demo-1808.id
  block_public_acls = false
  block_public_policy = false
}

# S3 public Read policy
resource "aws_s3_bucket_policy" "open_access" {
  bucket = aws_s3_bucket.terraform-demo-1808.id

  policy = jsonencode({
    Version = "2012-10-17"
    Id      = "Public_access"
    Statement = [
      {
        Sid = "IPAllow"
        Effect = "Allow"
        Principal = "*"
        Action = ["s3:GetObject"]
        Resource = "${aws_s3_bucket.terraform-demo-1808.arn}/*"
      },
    ]
  })
  depends_on = [ aws_s3_bucket_public_access_block.terraform-demo ]
}
```
**Step-5:** Configure the Output variable
Create a file named output.tf for your website's URL.

```
# Website URL
output "website_url" {
  value = "http://${aws_s3_bucket.terraform-demo-1808.bucket}.s3-website.${aws_s3_bucket.terraform-demo-1808.region}.amazonaws.com"
}
```
**Step-6:** Initialize your terraform
It essentially prepares Terraform’s working directory for managing infrastructure. It downloads and installs any required provider plugins based on your configuration like hashicorp/aws provider.

```
terraform init
```
**Step-7:** Terraform Validate
It performs a static analysis of your Terraform configuration files and validates the overall syntax of your Terraform code, ensuring it adheres to the Terraform language rules.

```
terraform validate
```
**Step-8:** Terraform Plan
It is used for understanding and reviewing the intended changes to your infrastructure before actually applying them.

```
terraform plan
```
**Step-9:** Terraform Apply
The Terraform apply command in Terraform is the one that actually executes the actions outlined in the plan generated by the Terraform plan. It’s the final step in making the desired infrastructure changes a reality.

```
terraform apply
```
**Step-10:** Access your website
After the apply process completes terraform will output your website's URL. Visit the URL to see your static website live.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwurje5mkpud5t3eqldh.jpg)

**Conclusion:**
Congratulations! You've successfully hosted a static website on Amazon S3 using Terraform. This approach not only makes deployment straightforward but also ensures your infrastructure is version-controlled and easily reproducible.

By following this guide, you can quickly deploy static websites for various purposes, such as personal blogs, portfolios, or documentation sites. Explore the power of Infrastructure as Code with Terraform and take your web hosting to the next level!