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.
- 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 :
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
# 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 :
Let’s clone the project into some other directory .
[shell]git clone file:///opt/testweb mywebsite[/shell]
After adding and committing new code files in the repo , Let’s push the changes to the “ prod “ branch of the server :
[shell]git push origin master:prod[/shell]
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.