Deploying a Static Website on AWS S3 Using Terraform
In this post, I'll walk you through how I set up and host a static website on AWS S3 using Terraform. The code below creates an S3 bucket, configures it for static website hosting, and manages access control for public availability.
10/2/20243 min read
Conclusion
This Terraform script automates the entire process of setting up an S3 bucket for static website hosting. It manages everything from creating the bucket to configuring access controls and uploading website files. Using Terraform's infrastructure as code capabilities allows you to version control and replicate this setup for future projects efficiently.
This Terraform code is available to download at my Github repo: github.com/tales-menezes/Static_Website.git
1. Creating the S3 Bucket
In the first step I create the S3 bucket, which will store the website files. Here, the bucket attribute uses a variable (var.bucket_name) for the bucket's name.
By abstracting the bucket name, I can reuse this code in the future for different projects by simply changing the value of the variable.
2. Managing Ownership Controls
AWS introduced ownership controls to specify who should own objects uploaded to a bucket. In this case, I ensure that the bucket owner has ownership of all objects.
This ensures that any objects uploaded to the bucket are owned by the bucket owner, rather than the uploader.
3. Public Access Configuration
By default, AWS restricts public access to S3 buckets for security reasons. Since it's a public static website, I adjusted the public access settings.
Here, I disable the default blocks to allow the public to access the bucket contents.
4. Setting Permissions with ACL
To allow the public to read the website files, I used an Access Control List (ACL) to grant public read permissions. This step is necessary to make the website publicly accessible.
I also set the proper dependencies to ensure that ownership controls and public access are configured before the ACL is applied.
5. Creating a Bucket Policy
In addition to setting public-read permissions with ACL, I created a bucket policy that explicitly allows public access to all objects in the bucket.
This policy grants anyone (i.e., "Principal": "*") the permission to retrieve ("Action": "s3:GetObject") objects from the bucket.
6. Enabling Static Website Hosting
Next, I enable static website hosting on the S3 bucket and specify the default pages for successful and error responses:
This configures the S3 bucket to serve index.html as the default page and error.html for any errors.
7. Uploading Website Files
Finally, I upload the index.html and error.html files to the S3 bucket:
This Terraform configuration ensures the index.html and error.html files are uploaded to the root of the bucket and are properly recognized as HTML files.
Cloud Professional
Optimizing cloud solutions for security and performance.
need a cloud solution?
Let's have a chat:
© 2024. All rights reserved.