Lightning intro: Fabric

Fabric is a nifty Python tool to automate deployment and system tasks. You define the commands you want to be able to use in fabfiles: a file called fabfile.py, or a directory (with __init__.py) called fabfile, either under the current working directory or X levels higher. This lets you define different fabfiles for different projects.

One thing I'm planning to use it for is quickly adding my RSA key to development servers. With a fabfile that looks like:

from fabric.api import run, put

def prepare_ssh()
    run('if [ ! -e /root/.ssh ]; then mkdir /root/.ssh; fi')
    put(local_path='/home/erik/.ssh/id_rsa_dev.pub', \
                   remote_path='/root/.ssh/id_rsa_dev.pub')
    run('cat /root/.ssh/id_rsa_dev.pub >> /root/.ssh/authorized_keys')


and a .fabricrc in my home directory that looks like:

user = root
key_filename = /home/erik/.ssh/id_rsa_dev


I can use this as:

fab -H [ipaddress1],[ipaddres2],[ipaddress3] prepare_ssh


This will copy my RSA key to the remote hosts, enabling me to login as root without a password. Should I define other commands, Fabric won't even ask me for a password anymore: thanks to the .fabricrc file it will try to log in as root with the specified ssh key.