I wrote a script that uploads all files and sub-directories of a root directory.
resource "aws_s3_bucket" "My_bucket" {
bucket = "testing-testing-testing-testing"
tags = {
Name = "My bucket"
}
}
resource "aws_s3_bucket_public_access_block" "public_bucket_access" {
bucket = aws_s3_bucket.My_bucket.bucket
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
depends_on = [ aws_s3_bucket.My_bucket ]
}
resource "aws_s3_bucket_policy" "bucket_policy" {
bucket = aws_s3_bucket.My_bucket.bucket
# Terraform's "jsonencode" function converts a
# Terraform expression's result to valid JSON syntax.
policy = jsonencode({
Version = "2012-10-17"
Id = "MYBUCKETPOLICY"
Statement = [
{
Sid = "PublicRead"
Effect = "Allow"
Principal = "*"
Action = [
"s3:GetObject"
]
Resource = [
"${aws_s3_bucket.My_bucket.arn}/*",
]
},
]
})
depends_on = [ aws_s3_bucket_public_access_block.public_bucket_access ]
}
resource "aws_s3_object" "object" {
for_each = fileset("${path.module}/travel-agency-html-template", "**/*")
bucket = aws_s3_bucket.My_bucket.bucket
key = basename(each.value)
source = "${path.module}/travel-agency-html-template/${each.value}"
etag = filemd5("${path.module}/travel-agency-html-template/${each.value}")
}
resource "aws_s3_bucket_website_configuration" "travel_agency" {
bucket = aws_s3_bucket.My_bucket.bucket
index_document {
suffix = "index.html"
}
error_document {
key = "404.html"
}
depends_on = [ aws_s3_object.object ]
}
It does it. But when I access the endpoint URL of the website, it takes me to download a file. Instead of opening the actual website. I don't know what's wrong with my code. I'd appreciate more insights on what I could be doing wrong.
Add content-type to your objects:
resource "aws_s3_object" "object" {
for_each = fileset("${path.module}/travel-agency-html-template", "**/*")
bucket = aws_s3_bucket.My_bucket.bucket
key = basename(each.value)
source = "${path.module}/travel-agency-html-template/${each.value}"
etag = filemd5("${path.module}/travel-agency-html-template/${each.value}")
content_type = "text/html"
}
Depending on your files, you may need to adjust content_type
for different files, e.g. json files would be application/json
.