Automating Deployment Tasks with Fabric
Fabric is a Python library for executing shell commands locally and
remotely over SSH. It is commonly used to automate deployment workflows
and operational tasks.
Typical Manual Deployment Workflow
A common deployment process looks like this:
- Commit and push changes to GitHub.
- SSH into the production server.
- Navigate to the project directory.
- Pull the latest changes from the repository.
- Back up the database (when required).
- Run database migrations.
- Update static assets.
- Perform other project-specific tasks.
These steps are repetitive and slow down development work.
Fabric automates these tasks by allowing you to define deployment
commands in a Python script and execute them from your local machine.
Installation
This example uses Ubuntu 16.04, but Fabric works on Windows and
other systems as well.
Install using apt
sudo apt-get install fabric
Install using pip
pip install fabric
After installation, the fab command becomes available.
Basic Usage
Fabric looks for a file named fabfile.py in the current project
directory.
This file defines tasks written in Python.
Example minimal fabfile.py:
from fabric.api import *
def reboot_server():
pass
def another_task(argument=''):
pass
Run a task from the terminal:
fab reboot_server
Pass arguments to tasks:
fab another_task argument:"some_value"
Recommendation: place fabfile.py at the root of the project.
Core Fabric Operations
Fabric provides several functions for executing commands.
These are available through fabric.operations.
run
Execute commands on a remote server through SSH.
result = run("ls ~/project")
Returned object attributes:
result.failed---Trueif the command failedresult.succeeded---Trueif successfulresult.command--- the executed command
sudo
Execute a command with elevated privileges on the remote machine.
result = sudo("apt-get install cowsay")
Behavior is identical to run, but with sudo privileges.
local
Execute a command on the local machine where Fabric runs.
local("ls ~/project")
Key characteristics:
- Runs locally instead of remotely.
- Does not return command output.
local is implemented using Python's subprocess module. For complex
local execution logic, consider using subprocess directly.
Fabric Context Managers
Context managers simplify command execution within specific directories
or environments.
They are available in fabric.context_managers.
cd
Change the working directory on the remote server for commands
inside the block.
Without context manager:
run('cd /var/www')
run('ls')
run('mkdir dir')
Using cd:
from fabric.context_managers import cd
with cd('/var/www'):
run('ls')
run('mkdir dir')
This translates internally to:
cd /var/www && ls
cd /var/www && mkdir dir
lcd
lcd works like cd, but changes the working directory on the local
machine.
It is typically used with local commands.
Environment Variables
Fabric stores shared configuration inside the env dictionary.
Location:
fabric.state.env
Commonly used attributes:
env.hosts--- list of remote serversenv.user--- SSH usernameenv.password--- SSH password (not recommended)
Example configuration:
from fabric.api import *
env.hosts = [
'www.example.com',
]
env.user = "username"
# Avoid storing passwords directly.
# Prefer SSH keys.
# env.password = "password"
Example Fabric Script
Complete fabfile.py example:
from fabric.api import *
from fabric.context_managers import cd
env.hosts = [
'www.example.com',
]
env.user = "username"
def first_task():
"""Update system packages"""
run("sudo apt-get update")
run("sudo apt-get -y upgrade")
def second_task():
"""Create directories inside /var"""
with cd('/var'):
run('mkdir dir1')
run('mkdir dir2')
Run both tasks:
fab first_task second_task
Why Use Fabric
Fabric is useful when a workflow involves repetitive command
sequences, such as:
- Deployments
- Server provisioning
- Maintenance tasks
- Batch command execution across multiple servers
Advantages:
- Tasks are defined in Python.
- Easy to compose complex workflows.
- Executes commands locally and remotely.
- Reduces manual operational work.
Next Steps
This article covered the fundamentals of Fabric.
More advanced setups typically include:
- SSH key authentication
- Structured configuration files
- Environment-specific deployments
One practical pattern is separating configuration into a file such as:
fabric.config.json
The Fabric script (fabfile.py) loads project-specific settings from
this configuration file.
Member discussion: