How to deploy static sites with git

As part of my contribution to a recent Random Hacks of Kindness event, I needed to put together a simple deployment mechanism for the static part of the site. The idea was to use a simple git push to trigger a deployment to production. There was a lot of documentation out here on the web about this, but there were many pitfalls along the way that I thought I'd document here to help others attempting to do the same.

So if you want to deploy static files to an EC2 instance using git and have a rollback archive to go back to then here is what you need to do. I'm going to assume that you've set up your EC2 instance to use Linux, and have chosen to serve files from /var/www/html and you will put your git repos into /var/git.

I'll further assume that your local machine is running Unix as well and that your private key for your EC2 instance is called examplekey.pem. If you're running Windows everything should work the same, but just look a bit different.

Prepare your server rollbacks

You just need some directories set up on your EC2 server - these just happen to be my preferences.

To get the above to work, you'll need to have your examplekey.pem registered with SSH (see earlier) or you'll get weird authentication errors. If you're really struggling you can attempt the SSH authentication manually with OpenSSL

$ ssh -v -i ~/.ssh/examplekey.pem ec2-user@1.2.3.4

This will shine a light on any problems that you'll otherwise be scratching your head over.

Do the first push

If no-one has ever done this do an initial push of all data in the master branch (assuming that's where your production site content lives)

$ git push production +master:refs/heads/master

You must have a bare remote repo (see earlier) otherwise git will starting whining at you. If you need to convert a repo back to a bare one then do the following on the server repo, but you'll lose any files checked out from the remote repo.

Conclusion

Once this system was in place, the developers working on the static side of the project found that they were able to push their changes extremely rapidly out to the production site. This lead to very short turnaround times for minor tweaks to the site, and encouraged frequent updates. Very agile.