How to Automate server administration tasks with fabric

Fabric is a python library that leverages SSH to automate application deployment and system administration tasks.

It is very simple and easy to use yet very powerful in automating repetitive tasks.

In this tutorial we will learn about fabric and deploy a simple django application using fabric.

INSTALLING FABRIC

Installing fabric via pip.

pip install fabric

By convention all our functions and configurations should be saved in a file called fabfile.py. If you decide to give this file any other name, then you will have to specify the path to where the file is using the -f flag.

fab -f <path to your fabfile>

Hello world program using Fabric

from fabric import task
 
@task
def hello(ctx):
  print("Hello World")

We must first import the task decorator from fabric and decorate our task with this decorator.

To be able to run the task we also need the context argument since fabric uses the invoke task() method which expects a context argument. ctx is just an abbreviation for context. You can also name it differently. To learn more about context argument check this link.

To run this task we use the fab command line tool followed by the name of our task.

fab hello

We get the following output.

Hello World

How to execute a shell command on a remote system via SSH

Fabric supports both RSA key authentication and password authentication. In this example we will use password authentication, but you can use RSA keys authentication by setting the key_filename path argument in the connect_args set of keyword arguments. Check the full documentation on authentication here

from fabric import task
from fabric import Connection


@task
def kernelname(ctx):
        c = Connection(host='172.28.128.6', user="vagrant", connect_kwargs={"password": "vagrant"})
        result = c.run('uname -s')

Fabric’s Connection class enables connection to SSH and has methods for both files transfer to a remote host and executing shell commands on remote hosts

The run method of the Connection class is specifically used to execute a shell command on a remote host. As seen in the above example we are using the run method to execute the “uname -s” command which gives us the kernel name of the remote host.

You can view the availabe tasks in your fabfile by running fab command with –list flag.

fab --list
fabkernelname

Lets execute another command on the remote host, this time, we will list files in the directory of our choice in the remote machine.

We can use the failed attribute of the result object to check if our command execution failed or not. On fail it is set to True while on success it is set to false.

@task
def list_files(ctx):
        c = Connection(host='172.28.128.6', user="vagrant", connect_kwargs={"password": "vagrant"})

        result = c.run("ls -l ~/codingfalcon/")

        print(result.failed)
listfiles

Running remote commands as superuser.

To run a command remotely as a superuser, you must use the sudo method of the Connection class.

In this command we will perform an update in a remote ubuntu server.

import getpass
from fabric import Connection, Config, task

@task
def run_sudo(ctx):
        sudo_passwd = getpass.getpass("Enter sudo password: ")
        config = Config(overrides={'sudo': {'password': sudo_passwd}})
        c = Connection(host='172.28.128.6', user="vagrant", config=config,  connect_kwargs={"password": "vagrant"})
        result = c.sudo("apt update")
        print(result.failed)

We can either use getpass to ask for the sudo password or set it in sudo.password as a configuration file

sudo

Running commands on your Local system with fabric

To run commands on your local system we use the local method of the connection class as shown below.

@task
def get_local_kernel_name(ctx):
        c = Connection(host='172.28.128.6', user="vagrant", connect_kwargs={"password": "vagrant"})
        result = c.local("uname -s")
        print(result.failed)

The above code will run the “uname -s” command on your local system.

Using fabric to transfer files.

To transfer files to a remote server we use the put method of the connection class.

@task
def transfer_files(ctx):
        c = Connection(host='172.28.128.6', user="vagrant", connect_kwargs={"password": "vagrant"})
        result = c.put("testfile.txt", remote="/home/vagrant/test")
        print(f"Uploaded {result.local} to {result.remote}")
put

To download files to a remote server we use the get method of the Connection class.

@task
def transfer_files(ctx):
        c = Connection(host='172.28.128.6', user="vagrant", connect_kwargs={"password": "vagrant"})
        result = c.get(remote="/home/vagrant/test/testfile.txt", local="/home/david/testfabric/")
        print(f"Downloaded {result.remote} to {result.local}")
get

In the above example we downloaded testfile.txt from our remote server to our local machine.

This tutorial gave you an introduction to tasks automation with fabric. You can check out the full fabric documentation here

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x