Hello everyone! I’m back with another Terraform course in the learning series. After completing a previous project, I decided to try something different – hosting a static website using AWS S3 and Terraform. I thought it would be cool to host a simple portfolio website (just a dummy website for practice 😄).
What am I building 🎯
I want to create a simple setup where:
- S3 bucket hosting my website
- Anyone can view this site (public access)
- It shows a nice portfolio page
- There’s error handling (you know, 404 and stuff like that)
Code and what I learned 📝
Let me show you the code I use and explain what I know about each part!
Configure S3 bucket
resource "aws_s3_bucket" "mybucket" {
bucket = var.bucket_name
}
This will create our basic S3 bucket. It starts simple, 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 items in the bucket. Trust me, I was a little confused by this at first!
public bucket
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 is 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.
Set up 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 archives to S3. I created a simple portfolio page with some dummy content and images.
Configure 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 as a web server. Storage services can host websites, which is cool, right? 🤓
What did I learn 📚
- S3 is actually great for hosting static websites
- Exposing information in AWS requires several steps (they really care about security!)
- Terraform makes it easy to recreate the entire setup
- Content types are important – I had some weird problems when I forgot to set them!