Fabric: Getting Started Tutorial

Hopefully this may help someone else out there who is looking for a good excuse to use Fabric in anger. I install Fabric on my local Ubuntu desktop using:

sudo apt-get install fabric

With Fabric installed I created a new directory for playing around and inside that folder created a file named fabfile.py as follows:

from fabric.api import local, env, run
env.user = "jonny"
env.hosts = [
'mailhost1',
'mailhost2',
'mailhost3'
]
def uptime():
run('uptime')

With the file saved I ran it is as follows:

fab uptime

Fabric executes the uptime command on each of the specified hosts. and I can see/parse the output. No big deal?

Note 1: A prerequisite of the above is that you have used ssh-copy-id to each of the hosts you want to use (if you don’t understand this read up about it)
Note 2: A prerequisite of the below use of sudo is adding a line such as:


jonny   ALL=(ALL)       NOPASSWD: ALL

to the /etc/sudoers file on each host you want to manipulate using sudo/root commands. This can be time consuming but worth it in the long run.

So today I wanted to replace syslog with rsyslog, amend the rsyslog.conf file and start/stop the appropriate services so that syslogs are sent from 30 servers to a central syslog server.

I created a directory ‘deploy_rsyslog’ and in it created fabfile.py as follows:

from fabric.api import local, env, put, run, sudo, cd
env.hosts = [
'hostname1',
'hostname2',
'hostname3',
'hostname29',
'hostname30',
'hostname31'
]
def deploy_rsyslog():
sudo("yum -y install rsyslog rsyslog-mysql")
with cd('/etc'):
put('rsyslog.conf', '/etc', use_sudo=True)
sudo("if [ -e /etc/init.d/syslog ]; then /sbin/chkconfig syslog off; fi")
sudo("/sbin/chkconfig rsyslog on")
sudo("if [ -e /etc/init.d/syslog ]; then /etc/init.d/syslog stop; fi")
sudo("/etc/init.d/rsyslog start")

I also created a file rsyslog.conf in this same directory to be uploaded(put) to each server.

I ran the script as:

fab deploy_rsyslog

Points to notice:

  • We need to import functionality for put, sudo etc otherwise we get an error “NameError: global name ‘cd’ is not defined”
  • When putting my conf file I need to use_sudo=True as I do not have write permissions to /etc as my normal user
  • To reduce errors I wrapped some if logic around commands to ensure the commands are only run if necessary. Otherwise the whole script stops if a host does not have the SysV script for syslog

Conclusion:

Fabric appears to be a pretty useful tool in the armoury not just for saving time but for creating a library of repeatable deployment scripts.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>