Hosting a Static Website Using S3 in AWS with Terraform
Published: 2024-06-27 18:26:52

Hello Everyone!!here's a blog post on hosting a static website using Amazon S3 and Terraform.

---

## Hosting a Static Website on AWS S3 Using Terraform

Hosting a static website on AWS S3 is a cost-effective and efficient way to make your content accessible to the world. By using Terraform, an infrastructure as code tool, you can automate the setup process, making it repeatable and easy to manage. In this tutorial, we'll walk you through the steps to host a static website on AWS S3 using Terraform.

## What is Amazon S3?

Amazon S3 (Simple Storage Service) is a scalable object storage service provided by AWS. It allows users to store and retrieve any amount of data at any time. S3 is often used for backup, archiving, and hosting static websites due to its high durability, security, and cost-effectiveness.

### Prerequisites

1. **AWS Account**: You need an AWS account to create the necessary resources.
2. **Terraform**: Install Terraform on your local machine. You can download it from the [Terraform website](https://www.terraform.io/downloads.html).
3. **AWS CLI**: Install and configure the AWS CLI with your credentials.

## STEP 1: Setup the Terraform

To set up Terraform, install it from terraform.io, configure AWS CLI, create a main.tf file with your infrastructure code, then run `terraform init` and `terraform apply`.

```
`terraform {
  required_version = "1.7.4"
  required_providers {
    aws = {
        source = "hashicorp/aws"
        version = "5.40.0"
    }
  }
}
provider "aws" {
  profile = "default"
  region = "ap-south-1"
} `

```
## STEP 2: Configuration for S3 Buckets:

Create an S3 bucket in Terraform with `aws_s3_bucket`, set `bucket` name, `acl` to "public-read", and `website` configuration. Add a policy with `aws_s3_bucket_policy` for public access.

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

#Upload file to S3
resource "aws_s3_object" "terraform_index" {
  bucket = aws_s3_bucket.terraform-demo-43234.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-43234.id

  index_document {
    suffix = "index.html"
  }
}
```

## step 3: configuration for bucket policy

Create a ‘policy.tf’ file to store the terraform configuration related to the bucket policy for public access.

```
#S3 public access
resource "aws_s3_bucket_public_access_block" "terraform-demo" {
    bucket = aws_s3_bucket.terraform-demo-43234.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-43234.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-43234.arn}/*"
      },
    ]
  })
  depends_on = [ aws_s3_bucket_public_access_block.terraform-demo ]
}

```

## step 4:Configuration for Output variable

This is an optional step. We are doing this to get a static website URL which we can also get through AWS Console. Create an ‘output.tf’ to print out the URL to access the website.

```
# Website URL
output "website_url" {
  value = "http://${aws_s3_bucket.terraform-demo-43234.bucket}.s3-website.${aws_s3_bucket.terraform-demo-43234.region}.amazonaws.com"
}
```

## Step 5: Initialize Terraform

To initialize Terraform , navigate to the directory containing your Terraform configuration files and run `terraform init`. This command initializes the environment, downloads necessary plugins, and prepares Terraform to manage your infrastructure according to the configuration defined in `main.tf`.

```
terraform init
```

## Step 6: Terraform Validate

```
terraform validate
```
Terraform files in your project directory are verified for syntax and configuration using the `terraform validate` command. Without actually running the configuration files, it checks them for problems. By doing this, you can make sure that before making any modifications to your infrastructure, your Terraform settings follow the proper syntax and structure.

## Step 7: Terraform Plan

```
terraform plan
```
Go to the directory of your project and execute the command `terraform plan' to create a Terraform execution plan. By comparing the desired state specified in your configuration files (`main.tf') with the present infrastructure state, Terraform suggests actions (create, update, and remove). Before using `terraform apply` to apply changes, review the plan.

## Step 8: Terraform Apply

```
terraform apply
```
To apply Terraform configuration changes, run `terraform apply`. Terraform will show a plan of actions to be performed based on your `main.tf` file. Confirm with `yes` to execute changes, creating or updating resources as specified.

## Step 9: Destroy

```
terraform destroy
```
The terraform destroy command in Terraform serves the purpose of tearing down the infrastructure resources that your Terraform configuration currently manages.

### Conclusion

Congratulations! You've successfully hosted a static website on AWS S3 using Terraform. This setup is highly scalable, cost-effective, and easy to manage. By using Terraform, you can version control your infrastructure and make deployment a breeze.Happy hosting!