5 min read

Fabric is a Python library that makes it easy to run scripts over SSH. Fabric currently supports Python 2.5 – 2.7 but not Python 3 yet. Fabric has great documentation so you can also check out their site

Why Use Fabric?

Fabric is great to use because it makes executing commands over SSH super easy. I think the Fabric tutorial explains it best.

  • Fabric is a Python (2.5-2.7) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.
  • More specifically, Fabric is:
    • A tool that lets you execute arbitrary Python functions via the command line;
    • A library of subroutines (built on top of a lower-level library) to make executing shell commands over SSH easy and Pythonic.
  • Naturally, most users combine these two things, using Fabric to write and execute Python functions, or tasks, to automate interactions with remote servers.

What I Use Fabric For

At my job, we use Fabric as an API to interact with our servers. We can deploy apps from any of our servers using a series of fab tasks.

Installing Fabric

The first thing you’ll want to do when you start building your first Fabfile is to install Fabric.

$ pip install fabric

If you haven’t used pip before you can find out more here

But basically, pip is a package manager for Python libraries.

Write Your First Fabfile

Ok! Let’s start writing this Fabfile.

In your project’s root directory (You can actually do this anywhere but I’m assuming you are using Fabfile for a specific project).

$ touch fabfile.py

Then in fabfile.py:

def add(a, b):
        print int(a) + int(b)

In your console, run:

$ fab add:1,2

Congratulations! That’s your very first fab command. One thing to notice is the way you pass arguments to the fab task. Now, in your console, run:

$ fab --list

You should see an output of your fab tasks you can run. This comes in handy when your Fabfile gets larger. This isn’t very interesting yet…

Write Your First More Useful Fabfile

One of the very first things I learned to do with command line was ls. In order to run ls on using Fabfile we just do the following:

from fabric.api import run, env

    def sub_list_files():
        run("ls")

Now, if I run:

$ fab -H [host_name] sub_list_files

This is the same as me doing:

$ ssh [host_name]
    $ ls 
    $ exit

Ok, so it’s not that exciting yet.

But let’s say I love adding and removing files and checking to make sure things happened the way I intended.

from fabric.api import run

    def sub_list_files():
        run("ls")

    def sub_create_file(name):
        run("touch " + name)

    def sub_remove_file(name):
        run("rm " + name)

    def create_file(name):
        sub_create_file(name)
        sub_list_files()

    def delete_file(name):
        sub_remove_file(name)
        sub_list_files()

Instead of running:

$ ssh [host_name]
    $ touch my_super_cool_file.py
    $ ls
    $ exit

 I can just do:

$ fab -H [host_name] create_file:my_super_cool_file.py

OR:

$ fab -H [host_name] sub_create_file:my_super_cool_file.py sub_list_files

Fabric with Different Environments

So let’s say I have one virtual machine that I need to SSH into often and I don’t want to have to keep using the -H flag. I can set the host name in my fabfile.

from fabric.api import env, run
    
    env.hosts = ['nameof.server']

    def sub_list_files():
        run("ls")

Now instead of having to set the -H flag I can just use:

$ fab sub_list_files

Now let’s say I have multiple environments. I’ll need a way to differentiate between which environment I want to work in. For this example, let’s say you have 2 servers. You have ‘staging’ and ‘production’. with something.staging.com and something.production.com associated with them. You’ll want to be able to use:

$ fab staging sub_list_files

And:

$ fab production sub_list_files

In order to get this working we just have to add the following code to our file.

from fabric.api import env, run
    
    env.hosts = ['staging.server', 'production.server']

    def sub_list_files():
        run("ls")

Now when you run $ fab sub_list_files Fabric loops over all the servers and runs ls on all the servers in the env.hosts array.

You probably don’t want to run commands across all of your servers everytime you run fab commands. In order to specify which server you’d like to communicate with you’ll just need to restructure slightly by replacing:

env.hosts = ['staging.server', 'production.server']

with:

def staging():
        env.hosts = ['staging.server']

    def production():
        env.hosts = ['production.server']

Now, you can call: 

$ fab staging create_file:my_cool_file.py

Fabric Fun

The documentation for Fabric is pretty good. So I do suggest reading through it to see what the Fabric API has to offer. One thing I found to be fun is the colors module.

from fabric.colors import red

    def hello_world():
        print red("hello world!")

This will print a red ‘hello world!’ to your console. Neat!

I encourage you to have fun with it. Try and use Fabric with anything that requires you to SSH.

About the Author

Liz Tom is a Creative Technologist at iStrategyLabs in Washington D.C. Liz’s passion for full stack development and digital media makes her a natural fit at ISL. Before joining iStrategyLabs, she worked in the film industry doing everything from mopping blood off of floors to managing budgets. When she’s not in the office, you can find Liz attempting parkour and going to check out interactive displays at museums.

LEAVE A REPLY

Please enter your comment!
Please enter your name here