static-website-hosting-S3-Terraform
This Terraform configuration sets up an AWS S3 bucket with the following features:
- Publicly accessible website hosting.
- Two HTML files (
index.html
anderror.html
) uploaded as S3 objects. - Bucket configured to serve as a static website.
- Public access granted via bucket policy and ACL.
- Ownership controls set to "BucketOwnerPreferred".
Ensure you have the following before applying this configuration:
- Terraform installed on your machine.
- AWS CLI installed and configured with appropriate credentials.
- An
index.html
anderror.html
file available in the same directory as the Terraform configuration.
- index.html: The main page of the static website.
- error.html: The error page displayed for invalid paths.
- main.tf: Contains the Terraform configuration.
-
S3 Bucket
- Change the name of
default = "replace_me"
in variable.tf.
- Change the name of
-
S3 Objects
- Uploads
index.html
anderror.html
to the bucket. - Sets
Content-Type
astext/html
andContent-Disposition
toinline
.
- Uploads
-
Public Access Block
- Configures the bucket to allow public access.
-
Bucket Policy
- Grants public read access to all objects in the bucket.
-
Ownership Controls
- Sets the ownership preference to
BucketOwnerPreferred
.
- Sets the ownership preference to
-
Website Configuration
- Configures the bucket for static website hosting with
index.html
as the index document anderror.html
as the error document.
- Configures the bucket for static website hosting with
-
Bucket ACL
- Sets the ACL to
public-read
to make the bucket publicly accessible.
- Sets the ACL to
- The bucket policy depends on the public access block to ensure proper sequencing.
- The ACL configuration depends on the ownership controls to avoid conflicts.
- Place the
index.html
anderror.html
files in the same directory as the Terraform configuration file. - Initialize Terraform:
terraform init
- Validate the configuration:
terraform validate
- Apply the configuration:
Review the plan and type
terraform apply
yes
to confirm. - Access the static website using the bucket's website endpoint (visible in the Terraform output or AWS Management Console).
- Ensure your HTML files are present before running
terraform apply
. - Make sure your AWS IAM user or role has sufficient permissions to create S3 resources.
- To avoid incurring unnecessary costs, remember to destroy the resources when they are no longer needed:
terraform destroy