Date:

Creating a Static Website with Terraform and AWS S3

Here is the rewritten article:

What I’m Building

I wanted to create a simple setup where:

  • An S3 bucket hosts my website
  • Anyone can view the website (public access)
  • It shows a nice portfolio page
  • Has error handling (you know, for 404s and stuff)

The Code and What I Learned

Let me show you the code I used and explain what I learned about each part!

Setting Up the S3 Bucket

resource "aws_s3_bucket" "mybucket" {
  bucket = var.bucket_name
}

This creates our basic S3 bucket. Pretty simple start, right?

Bucket Ownership Settings

resource "aws_s3_bucket_ownership_controls" "example" {
  bucket = aws_s3_bucket.mybucket.id

  rule {
    object_ownership = "BucketOwnerPreferred"
  }
}

I learned that this part is important because it helps manage who owns the objects in the bucket. Trust me, I had some confusion about this at first!

Making the Bucket Public

resource "aws_s3_bucket_public_access_block" "example" {
  bucket = aws_s3_bucket.mybucket.id

  block_public_acls = false
  block_public_policy = false
  ignore_public_acls = false
  restrict_public_buckets = false
}

This was tricky! By default, AWS makes everything private (which is good for security). But since we want people to see our website, we need to make it public.

Setting Up the Website Files

resource "aws_s3_object" "index" {
  bucket = aws_s3_bucket.mybucket.id
  key    = "index.html"
  source  = "index.html"
  acl     = "public-read"
  content_type = "text/html"
}

resource "aws_s3_object" "error" {
  bucket = aws_s3_bucket.mybucket.id
  key    = "error.html"
  source  = "error.html"
  acl     = "public-read"
  content_type = "text/html"
}

resource "aws_s3_object" "profile" {
  bucket = aws_s3_bucket.mybucket.id
  key    = "setchuko.jpg"
  source  = "setchuko.jpg"
  acl     = "public-read"
}

This part uploads our website files to S3. I created a simple portfolio page with some dummy content and an image.

Configuring Website Hosting

resource "aws_s3_bucket_website_configuration" "website" {
  bucket = aws_s3_bucket.mybucket.id

  index_document {
    suffix = "index.html"
  }

  error_document {
    key = "error.html"
  }
}

This tells S3 to act like a web server. Pretty cool that a storage service can host websites, right?

What I Learned

  • S3 is actually pretty awesome for hosting static websites
  • Making things public in AWS requires a few steps (they really care about security!)
  • Terraform makes it easy to recreate the whole setup
  • Content types are important – got some weird issues when I forgot to set them!

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here