Skip to content
YTEC

Insights

Teaser into automation with Fabric talk

YTEC Tech Talks #2: automating tasks with Fabric and handling database migrations.

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 to deal with those tasks, one of which is Fabric, a neat Python module for running shell commands locally and over SSH. The examples below use the Fabric 1.x API (fabric.api). It's quite simple to start:

1# fabfile.py
2import os
3from fabric.api import task, local, lcd, env
4
5env.project_root = os.path.dirname(env.real_fabfile)
6
7@task
8def virtual_create(version='python3.6'):
9 with lcd(env.project_root):
10 local('virtualenv -p %s virtual' % version)
11

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

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

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

1# [...]
2@task
3def virtual_update():
4 with lcd(env.project_root):
5 if os.path.exists('requirements.txt'):
6 local('virtual/bin/pip install -r requirements.txt')
7 else:
8 print('Cannot find file requirements.txt')
9

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:

1# fabfile.py
2from fabric.api import task, run, env
3
4env.hosts = ['bob@10.50.20.113']
5
6@task
7def miser(key='pcpu', top='5'):
8 """Inspect, who is the biggest 'miser' process"""
9 run('ps aux --sort=-%s | head -n %s' % (key, top))
10

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 to simplify and speed up your workflow or prevent unnecessary bugs. Wouldn't it be nice to have a command that sets up and starts a local development 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 the second edition of our Tech Talks.