Fabric a Great Tool to Automate Mundane Tasks

This is a late post, few months back I had to update a certain firmware for a logger device on to hundreds of the devices. For some reason at that time the OTA update mechanism which was already implemented on those devices did not work. As it was crucial to update all the devices as soon as possible, some work around for this problem had to be found.

The update procedure was actually simple, you login to the device using ssh, execute the update script and restart the device. But to do this process for each device (hundreds of those) is a really boring and time consuming job.

From previous Python Meetups I had an idea about fabric but I never had a chance to use it. Now I thought this is a good opportunity for me to try this great library/tool whatever you may want to call it.

So here is my setup.

I had a script to make updates on the remote systems which needed following arguments as the command line arguments.

  • server IP
  • server port
  • (archive) file to be downloaded
  • Directory containing the firmware.

The solution

The way it works is, the fabric comes with a tool called fab it looks for the fabfile. You have to write your deployment logic in fabfile.py As I had to run only one command on the remote machine it was really simple, the fabfile.py looked like this.

#! /usr/bin/python

from fabric.api import run
serverIp   = "192.168.1.1"
serverPort = "8000"
filename   = "MyFIle.tar.gz"
dirName    = "MyDir"

def makeUpdate():
    run("/bin/update.sh {0} {1} {2} {3}".format(serverIp, serverPort, filename, dirName))

Where you import run module from fabric.api and whatever you pass it; gets executed on the remote machine.

To execute this script the command is

fab -H <remoteIP> -u <username> -I makeUpdate

What this command does is:

  • logs in to the remote machine with the specified user name
  • calls the function you have passed to the argument -I

Here in this case the argument to -I is makeUpdate therefore the makeUpdate function is called where we have executed update.sh.

Executing it on all of the devices.

Writing the fabfile is only one part of the solution. I had to run this for all of the devices. So I wrote another python script (although this could be done using shell script).

This python script looks like.

#! /usr/bin/python
import os
clients =  open("clients.txt").read().strip().split("\n")

print("updating following machines")
for i in clients:
    if i:
        print(i)

for i in clients:
    os.system("fab -H {0} -u root -I makeUpdate".format(i))

Fabric is a great tool, really simple to understand and use; saved me a lot of time.

comments powered by Disqus