S3 static website with local Sync

S3 static website with local Sync

In this blog, I shall attempt to publish a simple static website to s3.

We are using CLI for this purpose. Make sure you have AWS cli installed in your terminal

aws configure

copy and paste AWS Access Key Id and Secret Access Key to your terminal

next, using s3api create a bucket

aws s3api create-bucket --bucket santoshmainali --region eu-west-1 --create-bucket-configuration LocationConstraint=eu-west-1

Remember to make the bucket name unique. I've given name santoshmainali in this case. If everything goes fine, you should encounter a json that says location and the urlof your bucket

now create a new folder for this demo and create a new static file called index.html or you can name it anyway you like

mkdir demo && cd demo
touch index.html

You can edit your index.html with vim or any text editor

Now let's configure the newly created bucket as a static website and indicate it should load index.html as it's starting file.

aws s3 website s3://santoshmainali/ --index-document index.html

Now we copy our index.html to the bucket recursively with the access control as public read

aws s3 cp . s3://santoshmainali/ --recursive --acl public-read

let's check whether or not the files were uploaded

aws s3 ls santoshmainali

in your amazon console, select your bucket's properties tab and scroll down to the Static Website Hosting section. Find the url and open it in new browser.

Congratulations! You have setup a static website with s3.

Let's implement baby CI :P

cd ~
touch ci.sh
vi ci.sh

now paste this inside your ci script

#!/bin/bash
aws s3 cp ~/demo/ s3://santoshmainali/ --recursive --acl public-read

Grant permissions to execute

chmod +x ci.sh

now whenever you change your index.html inside demo just execute the ci in your shell. It updates every single file.

Every single file ? Yes! It updates files that are not updated. Sucks right ?

S3 Sync on rescue

change index.html and dry run s3 sync

aws s3 sync demo/ s3://santoshmainali/ --dryrun

It should give your this output

(dryrun) upload: demo/index.html to s3://santoshmainali/index.html

cool ! only those files which had changes were shown in the dry run.

that was just a dry run. Whenever you want to replicate changes live, don't enable that flag. Also don't forget to give it appropriate acl

aws s3 sync demo/ s3://santoshmainali/ --acl public-read

You can add the new sync command to your ci .sh file I Hope it Helps. Feedback expected.