Deploying a static website on S3 with Terraform
Introduction
New week new quest! This will be a short article but funny to write (and read, I hope)!
Let's deploy a static website on AWS S3 with Terraform.
Static website goes dynamic
S3 Bucket deploy
If you want to deploy a static website on AWS S3, you must deploy a S3 bucket!
I will not be long on this :
resource "aws_s3_bucket" "example" {
bucket = "bucket-tf-example"
}
Publicly accessible
To make your website accessible, you must turn off all the ACL policies and publicly make your bucket object and resources available.
resource "aws_s3_bucket_ownership_controls" "example" {
bucket = aws_s3_bucket.example.id
rule {
object_ownership = "BucketOwnerPreferred"
}
}
resource "aws_s3_bucket_public_access_block" "example" {
bucket = aws_s3_bucket.example.id
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
S3 Static Website configuration
You need to configure your S3 bucket to serve your website to clients.
resource "aws_s3_bucket_website_configuration" "example" {
bucket = aws_s3_bucket.example.id
index_document {
suffix = "index.html"
}
}
The following lines :
index_document {
suffix = "index.html"
}
This tells AWS S3 that the base file is index.html. It will take it in your bucket (This needs to be in at the root level of your bucket) as the file to serve at the root level of your website.
Upload index.html on S3
To be able to version your index.html. And be sure your file is always uploaded. You can use Terraform to Upload your file.
resource "aws_s3_object" "object" {
bucket = aws_s3_bucket.example.id
key = "index.html"
source = "path/to/index.html"
etag = filemd5("path/to/index.html")
}
Manual step
There is one step that I should have done with Terraform. I tried to put acl = 'publi-read'
like this :
resource "aws_s3_object" "object" {
bucket = aws_s3_bucket.example.id
key = "index.html"
source = "path/to/index.html"
etag = filemd5("path/to/index.html")
acl = 'public-read'
}
This did not work on my side. If you have any idea how to make your s3 object publicly available, like when you are doing the following on the UI of AWS, please do not hesitate to drop a comment or send me a message!
Conclusion
Now you can deploy your static website with Terraform.
By managing your bucket ACL, adding website configuration, and dynamically uploading your static website file.
Also, I did not speak about it, but you can have different routing and paths thanks to the folder in your bucket.
Top comments (3)
Most probably, acl fails because the bucket restricts public access.
Yes that's it I had to edit it by hand thanks! I would have like to do it with Terraform though :)
I don't know the latest update. You can also set bucket policy. docs.aws.amazon.com/AmazonS3/lates...