AWS S3 Host Static Website

Updated 27/09/2024

I needed to pop a static website into a S3 bucket because its current containerised hosting in AWS Lightsail was proving to be problematic with new deploys (wierd javascript errors) and attracting a higher hosting cost. (EC2 compute to run the container service)

Lucky for me I work with legends who have already figured this out so most of the below is based on the work done by Jaco Brink - cheers brother!

AWS Config

The below assumes your AWS CLI is installed and configured.

Note the user will need permissions policies AmazonS3FullAccess and AWSCloudFormationFullAccess. Hopefully you add these via a user group and not attach directly like a moegoe 😐

Create the Bucket

Cloud formation is the weapon of choice when deploying infrastructure. Its repeatable and then managed by AWS.

The cloud formation template data here is kept in porky-bucket-website.json because YML hurts my brain.

porky-bucket-website.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Create s3 bucket and policy for Porky Website",
"Parameters": {
"BucketName": {
"Type": "String",
"Description": "Porky bucket website",
"Default": "porky-bucket-website"
}
},
"Resources": {
"MyS3Bucket": {
"Type": "AWS::S3::Bucket",
"Description": "Porky bucket website",
"Properties": {
"BucketName": {
"Ref": "BucketName"
},
"PublicAccessBlockConfiguration": {
"BlockPublicAcls": false,
"BlockPublicPolicy": false,
"IgnorePublicAcls": false,
"RestrictPublicBuckets": false
},
"WebsiteConfiguration": {
"IndexDocument": "index.html",
"ErrorDocument": "error.html"
}
},
"DeletionPolicy": "Retain",
"UpdateReplacePolicy": "Retain"
},
"MyS3BucketPolicy": {
"Type": "AWS::S3::BucketPolicy",
"Properties": {
"Bucket": {
"Ref": "MyS3Bucket"
},
"PolicyDocument": {
"Statement": [
{
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": [
{
"Fn::Sub": "arn:aws:s3:::${MyS3Bucket}"
},
{
"Fn::Sub": "arn:aws:s3:::${MyS3Bucket}/*"
}
],
"Principal": {
"AWS": [
"*"
]
}
}
]
}
}
}
}
}

Now run the cloudformation comand:

1
aws cloudformation create-stack --stack-name PorkyBucketWebsiteStack --template-body file://./aws-deploy/porky-bucket-website.json --profile infrauser --region ap-southeast-2

You can also run with update-stack to update.

Deploy website

Now after publishing your code to ./pub deploy it to the bucket.

1
aws s3 sync './pub' 's3://ums-audits' --acl public-read --profile infrauser --region ap-southeast-2

The DNS is avalible from the AWS Console -> Amazon S3 -> Buckets/porky-bucket-website -> Properties -> Static website hosting

By default this will not have HTTPS.

References