Thursday, October 22, 2009

Remote deployment with Fabric

Fabric is a Python module that allows to execute scripts on remote hosts. It uses configuration scripts to perform the tasks.

import re
import pysvn
from fabric.api import run, env

baseurl = ""

def site(  ):
    env.hosts = ['xxx.yyyypixel.com:22']
    env.user = 'jailed'
    env.baseurl = "http://pixelame.googlecode.com/svn/tags"

def deploy(  ):

    client = pysvn.Client()

    tagList = client.ls(env.baseurl)

    tagDict = {}

    while True:
        i = 0
        for k in tagList:
            name = k._PysvnDictBase__name
            tag = re.compile('[^/]*$').search(name).group()
            i += 1
            tagDict[i] = name
            print str(i) + ") " + tag

        key = input( "Tag to export " )
       
        key = int( key )

        if (  tagDict.has_key( key )) :
            url = tagDict[key]
            break
   
    print url
    run( 'svn export ' + url + ' /var/www/pixelame ') // this command is executed on remote host

   
To invocate this script use:

fab -f script.py site deploy   

Where script.py is the previous script and site and deploy are the methods that will be called. It connect thru ssh to the server and perform the subversion command on it with the method "run".
This is a very simple example, but fabric can perform very complex tasks.