Building a Static Website with Terraform: Step-by-Step Guide
Published: 2024-06-29 08:08:31

Creating and hosting a static website has never been easier with the power of Infrastructure as Code (IaC) and cloud services. In this guide, we'll walk you through setting up a static website using Terraform to manage AWS resources. You'll learn how to automate the creation of an S3 bucket, configure it for static website hosting, deploy your website files, and some additional considerations.

**Prerequisites**

Before we start, ensure you have the following:
• An AWS account.
• AWS CLI installed and configured with appropriate permissions.
• Terraform installed.

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

**Step 1: Initialize Your Project**

Create a new directory for your Terraform project and navigate to 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:

```
terraform {
  required_version = ">= 1.8.5"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.40.0"
    }
  }
}

provider "aws" {
  profile = "default"
  region  = "ap-south-1"
}
```
This configuration sets up Terraform to use the AWS provider, specifying your AWS profile and region.

**Step 3: Create the S3 Bucket**

Create a file named **bucket.tf** to define your S3 bucket and its configuration:

```
resource "aws_s3_bucket" "terraform_demo_102324" {
  bucket = "terraform-demo-102324-unique-id" # Ensure this bucket name is unique
}

resource "aws_s3_object" "terraform_index" {
  bucket       = aws_s3_bucket.terraform_demo_102324.id
  key          = "index.html"
  source       = "index.html"
  content_type = "text/html"
  etag         = filemd5("index.html")
}

resource "aws_s3_bucket_website_configuration" "terraform_hosting" {
  bucket = aws_s3_bucket.terraform_demo_102324.id

  index_document {
    suffix = "index.html"
  }
}

```
This defines an S3 bucket and uploads an index.html file to it, configuring the bucket for static website hosting.
create a file with name index.html(anyname)
for your index.html sample code:

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Terraform</title>
</head>
<body style="background-color: aquamarine;">
    <h1 style="color: azure;">Welcome to Terraform</h1>
</body>
</html>
```

**Step 4: Set Bucket Policies**

Create a file named **policy.tf** to define your S3 bucket policies for public access:

```
resource "aws_s3_bucket_public_access_block" "terraform_demo" {
  bucket                  = aws_s3_bucket.terraform_demo_102324.id
  block_public_acls       = false
  block_public_policy     = false
}

resource "aws_s3_bucket_policy" "open_access" {
  bucket = aws_s3_bucket.terraform_demo_102324.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_102324.arn}/*"
      },
    ]
  })

  depends_on = [aws_s3_bucket_public_access_block.terraform_demo]
}
```
This ensures your bucket's objects are publicly accessible.

**Step 5: Output the Website URL**

Create a file named **output.tf** to output your website's URL:

```
output "website_url" {
  value = "http://${aws_s3_bucket.terraform_demo_102324.bucket}.s3-website.${aws_s3_bucket.terraform_demo_102324.region}.amazonaws.com"
}
```
This outputs the URL of your hosted static website after deployment.

**Step 6: Deploy Your Static Website**
(i)open Windows PowerShell
**1**. Initialize Terraform:

```
terraform init
```
This command prepares your working directory for other Terraform commands.

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

**2**. Apply the Configuration:

```
terraform apply
```

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

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

**3**. Access Your Website:

After the apply process completes, Terraform will output your website's URL. Visit this URL to see your static website live.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xol6a3dhyjpg8k9sf0x8.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8bjo21ukm5uca51kq8i.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/biqp36t4knbhyi7l1coc.png)

**Additional Considerations**

• Custom Domain: To use a custom domain for your static website, you can set up Route 53 for DNS management and CloudFront for CDN and SSL/TLS termination.

• Versioning and Backup: Enable versioning on your S3 bucket to maintain backups of your files. This helps in case of accidental deletion or modification.

• Security: Review and implement appropriate security measures, such as bucket policies and IAM roles, to restrict access and protect your resources.

• Monitoring and Logging: Set up S3 access logging and CloudWatch alarms to monitor and manage your static website's performance and availability.

**Conclusion**

Congratulations! You've successfully deployed a static website using Terraform on AWS. By leveraging Infrastructure as Code, you can manage your resources efficiently and ensure consistency across deployments. This approach not only saves time but also enhances scalability and maintainability for your projects.

Feel free to explore more Terraform resources and customize your setup further. Happy coding!