I recently hosted a static website on AWS S3. This is pretty straight forward if you already have an AWS account and user/role configured with Adminstrator priviledges. You basically create a S3 bucket, make is public and upload your website content directly from the AWS console.
I had to tweak a couple of things on my journey and ended up re-doing some of the setup. Because of this I decided to see how to automate the infrastructure and also the content deployment process for when my static site needed updating.
TLDR
If you care less about the how and just want a quick template, go here:
aws-s3-website-template
Plan of Action
Here are the things we need to do:
- Install the AWS CLI and configure your AWS credentials. (your local PC)
- Create an infrastructure file that defines a publicly accessible S3 bucket.
- Create an infrastructure deployment script.
- Create a content deployment script
AWS CLI and config
You can install the AWS CLI from here.
Ensure you have your AWS config and credentials setup like this.
.aws/config
1 | [profile your-aws-profile] |
.aws/credentials
1 | [your-aws-profile] |
Infrastructure File
app.yml
1 | AWSTemplateFormatVersion: 2010-09-09 |
NOTE: You are have to upload an index.html
and error.html
file in order for the site work properly.
Infrastructure Deployment Script
We will use CloudFormation to create the S3 bucket by executing a bash script. Typically you only do this once and can opt to just create your bucket in the AWS console instead. I like doing this scripting route for the following reasons:
- It gives me an easy way to re create my bucket if something ever goes wrong. e.g. hackers or me
- Serves as a template for new projects. Easy to copy, paste and modify.
I created a deployInfra.sh
script that allows me to conditionally create or update the bucket.
The CloudFormation CLI command looks like this:
1 | aws cloudformation "$1" \ |
The $1
is an agument that is passed and can be either create-stack
or update-stack
.
See full script
1 | _defaultColor=$(tput sgr0) |
Content Deployment
S3 CLI comes with a really nifty command, sync
. This does all the heavy lifting for you by synchronizing a source content with your S3 bucket.
- Configure the website content as the source (on your pc)
- Configure the S3 bucket to sync to.
1 | aws s3 sync '/website-source-directory' 's3://MyS3BucketWebsite' \ |
I created a deployContent.sh
script that executes the sync
action.
See full script
1 | _defaultColor=$(tput sgr0) |