Teaser into automation with Fabric talk

7 juni 2018
#2 Tech Talk meetup

There is always room for improvement and especially in the world of ones and zeros you'll find yourself seeing more and more similar patterns and repetition of tasks emerging everywhere. There are different ways how to deal with those tasks - one of which is Fabric, a neat Python module. And it's quite simple to start:

# fabfile.py
import os
from fabric.api import task, local, lcd, env

env.project_root = os.path.dirname(env.real_fabfile)

def virtual_create(version='python3.6'):
    with lcd(env.project_root):
        local('virtualenv -p %s virtual' % version)

This gives us a Fabric command that we can easily use to create new virtual environments for our Python projects:

alice@alicepc:~/projects/myrepo$ fab virtual_create
[localhost] local: virtualenv -p python3.6 virtual
Running virtualenv with interpreter /usr/bin/python3.6
Using base prefix '/usr'
New python executable in /home/alice/projects/myrepo/virtual/bin/python3.6
Also creating executable in /home/alice/projects/myrepo/virtual/bin/python
Installing setuptools, pkg_resources, pip, wheel...done.


Similarly, we can add a command for updating our virtual environment:

# [...]
def virtual_update():
    with lcd(env.project_root):
        if os.path.exists('requirements.txt'):
            local('virtual/bin/pip install -r requirements.txt')
            print('Cannot find file requirements.txt')

Maybe you don't care too much about your Python environment. But what you do care for are your servers. You really need to improve the monitoring of your servers and like to view some quick stats from all your machines. Fabric can help you with that as well:

# fabfile.py
from fabric.api import task, run, env

env.hosts = ['bob@']

def miser(key='pcpu', top='5'):
    """Inspect, who is the biggest 'miser' process"""
    run('ps aux --sort=-%s | head -n %s' % (key, top))

And of course it doesn't end here. Quite the contrary - it just starts. Maybe you can already think of tasks you'd like to automate - simplify, speed up your work flow or prevent unnecessary bugs. Wouldn't it be nice to have a command, that would setup and start local dev. server? Or run all tests? Generate fake data for development (GDPR everywhere)? And why stop there, why not have a Fabric command, that would deploy the whole project?!

To get more detailed insight into what is possible and how we successfully use Fabric to do the repetitive work for us, come and visit our second round of Tech Talks.