Friday, June 6, 2014

Fabric fabfile for Varnish deploy and ban

This is the file I use for deploying new vcls and purging stuff from my caches. I've got load balancing with haproxy set up in front of three caches so deploy or purge needs to be done on all three caches pretty much at the same time. I've set up ssh keys on the hosts so I won't have to stuff the fabfile with passwords and such.

For more on my load balancing proxy set up, see this post.

The fabfile is kept in the same directory as I keep the default.vcl for the hosts.

To purge an url: fab purgeUrl:<urlpattern>
To purge a host:  fab purgeHost:<hostnamepattern>
To deploy default.vcl:  fab deploy

from __future__ import with_statement

import os.path
import time
from fabric.api import *
from fabric.contrib.project import *


"""
Environments
"""

def dev():
        env.hosts = ['host1','host2','host3']
        env.user = 'root'
        env.path = '/etc/varnish'

"Default to 'dev' environment"
dev()


"""
Tasks - Deployment
"""

def deploy():
        require('path', provided_by=[dev])
        with cd(env.path):
                put('default.vcl','default.vcl')
                programname = str(time.time())
                run('varnishadm -Tlocalhost:6082 -S/etc/varnish/secret vcl.load ' + programname + ' /etc/varnish/default.vcl')
                run('varnishadm -Tlocalhost:6082 -S/etc/varnish/secret vcl.use ' + programname)

def purgeHost(myHost):
        require('path', provided_by=[dev])
        with cd(env.path):
                run('varnishadm -Tlocalhost:6082 -S/etc/varnish/secret ban req.http.host == '+ myHost)

def purgeUrl(myUrl):
        require('path', provided_by=[dev])
        with cd(env.path):
                run('varnishadm -Tlocalhost:6082 -S/etc/varnish/secret ban "req.url ~ '+ myUrl +'"')

No comments:

Post a Comment