Simple Web Deployment With Mercurial And Fabric

I have been doing a lot of web development work lately. Mostly learning about how different people create their workflows and manage local development, testing, staging, and production deployment of code.

In the past I have used Apache Ant for deploying Java applications. It is a bit cumbersome. Apache Ant uses XML config files which are kind of limiting once you try to do something non-standard and can sometimes require writing special Java code to create new directives. The resulting XML is not always easy to read.

For the last few days I have been using Fabric to write a few simple deploy scripts and I think this is a much nicer way of doing it. You get the full power of Python but a very simple syntax and easy command line usage.

Here’s a very simple deploy script that I am using to deploy some static files to my web server.

from fabric.api import *
#Fabric 0.9.0 compatible
# usages: $ fab prod deploy
REMOTE_HG_PATH = '/home/halotis/bin/hg'
def prod():
    """Set the target to production."""
    env.user = 'USERNAME'
    env.hosts = ['']
    env.remote_app_dir = 'webapps/APPLICATION'
    env.remote_push_dest = 'ssh://' % env.remote_app_dir
    env.tag = 'production'
def deploy():
    """Deploy the site.
    This will tag the repository, and push changes to the remote location.
    require('hosts', provided_by=[prod, ])
    require('remote_app_dir', provided_by=[prod, ])
    require('remote_push_dest', provided_by=[prod, ])
    require('tag', provided_by=[prod, ])
    local("hg tag --force %s" % env.tag)
    local("hg push %s --remotecmd %s" % (env.remote_push_dest, REMOTE_HG_PATH))
    run("cd %s; hg update -C %s" % (env.remote_app_dir, env.tag))

For this to work though you need to have some things set up.

  • Need SSH access to the remote server
  • Mercurial (hg) must be installed on the remote server, and development
  • Need to bootstrap the remote repository – FTP the .hg folder to the destination location
  • Install Fabric on local development machine – $ pip install fabric

Find out more about Fabric from the official site.