Automating deployment of a static website hosted on Amazon S3

25 / Feb / 2014 by ravi 2 comments

Most of us know how to host a static website on Amazon S3, but to deploy the website you would need to run the AWS Cli command everytime manually.

In this blog I’ll show you how to automatically deploy your website while maintaining version control of your project using server side hook provided by Git.

Prerequisite :

  • Git
  • Aws Cli tool

Initializing a Git repository on your existing Project :

If you already have a git repository for your project then you may skip this step , else initialize a git repo on your project :

cd /opt/testweb
git init .

Creating  a hook to automatically upload the website

Here we’ll write a “post-receive” hook , which executes itself on the remote repository after all the refs have been updated. Hooks are located in the .git directory of your project under the hooks folder (.git/hooks).

Our post-receive hook looks somewhat like this :

# post-receive hook to upload to s3 bucket
#!/bin/bash
set -e
PROJ_DIR=$(dirname $PWD)
unset GIT_DIR
cd $PROJ_DIR
# Specify here , the branch whose code should be pushed to the bucket
git checkout prod
# aws cli command to sync the code
aws s3 sync $PROJ_DIR s3://my-first-website --delete --exclude ".git/*"
git checkout master

Few points to note here :

  • You need to specify the branch here whose code should be pushed to the bucket.
  • I am using sync command , so that update and delete happens accordingly to your working directory.
  • and the .git directory is excluded
  • Don’t forget to give executable permission to your hook.

Let’s Test it out !!!

For this blog, I have a simple html page as soon below hosted on my S3 bucket, which I’ll later update with a template :

html_page

Let’s clone the project into some other directory .

git clone file:///opt/testweb mywebsite

After adding and committing new code files in the repo , Let’s push the changes to the “ prod “ branch of the server :

git push origin master:prod

with this our hook will also get executed and on the terminal you would notice that the hook is uploading your files on your bucket :

Now Lets check the index.html page on our S3 bucket :

And here it is , so from now onward all you need is a simple PUSH :)

PS: This was a simple use of a git hook , you can hack it your way to do much more stuff.

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Desi music radio

    Howdy! Thiis is kind of off topic but I need some hslp from aan established blog.

    Is it difficult to set up your own blog? I’m not very techincal
    but I can figure things oout pretty quick. I’m thinking
    about making my own butt I’mnot sure where to start. Do you have any points or suggestions?
    Thanks

    my blog: Desi music radio

    Reply

Leave a comment -