google-prettify

Tuesday, August 6, 2013

Deploying websites using Git & Assembla

If you are hosting your website on a server to which you have SSH access, you can use Git to deploy changes to it.

Broadly speaking, the basic process is very simple - the server gets the code from the Git repository and then syncs it with the website. However there are a few issues worth considering when you implement this solution.

User Accounts

As we will be using Git over SSH, one thing that we will need to do is setup SSH keys between the Assembla Git repository and the server we will be deploying to - ie. make sure that the server can access the Git repository hosted on Assembla.

Here two 'user accounts' come into play - the Assembla user and the user on the server.

For deployment purposes rather than using an existing Assembla user's account, it is advantageous to use a special "deployment account". This ensures that the deployment process is not tied any particular user - who may or may not be part of the project down the line.

The other account that is on the server, is the one whose public key will be uploaded to Assembla and given access to the repository. You need to make sure that it has the necessary permissions and rights to do the deployment.

Setting up SSH keys

First thing you need to do is to login to the server with the user that you are going to be performing the deploy with; and get it's public SSH key, which should be present at ~/.ssh/id_rsa.pub OR ~/.ssh/id_dsa.pub. If it isn't you can generate one by using the following command:

ssh-keygen -t rsa -C "email@example.com"

Once you have the key file generated, open it using and copy all it's contents to your clipboard.

Now login to Assembla using your "deployment user", and upload the key.

Goto Profile > Manage SSH Keys > "Add a key, pasting it from clipboard."

Assembla profile page

Once the key is added you can also set this key to "Read-only Mode" here, as we are not expecting to make any commits using from this account.

Confirm the key is working by trying to do a clone (you will need to confirm the identity of the server).

Script to deploy

Now that we can access the git repository directly, a simple bash script will do the job of deploying the website:

mkdir -p ~/repos #make a "repos" directory where we will get the Git repository

cd ~/repos 

git clone <repo address goes here> # clone the repo (if required), if a repo is already there it will throw an error and go on

git pull #pull all the latest changes

git checkout master # checkout the branch you want to deploy from

rsync -avz ~/repos/src ~/htdocs/ # update the website

The above script is a rudimentry example, you can make alterations and additions as required.

If there is any other processes that you need to perform after a deploy, such as sending emails, clearing cache etc., they can easily be added in this script.

No comments:

Post a Comment