Last Updated: February 25, 2016
·
1.415K
· rcarmo

Manage Vagrant instances with Fabric

Here's a little stub to make it easier to run ad-hoc commands inside Vagrant instances:

from fabric.api import env, local, run

def vagrant():
    """Allow fabric to manage a Vagrant VM/LXC container"""
    env.user = 'vagrant'
    v = dict(map(lambda l: l.strip().split(),local('vagrant ssh-config', capture=True).split('\n')))
    # Build a valid host entry
    env.hosts = ["%s:%s" % (v['HostName'],v['Port'])]
    # Use Vagrant SSH key
    if v['IdentityFile'][0] == '"':
        env.key_filename = v['IdentityFile'][1:-1]
    else:
        env.key_filename = v['IdentityFile']

def uname():
    """Classic example"""
    run('uname -a')

And here's the result:

$ fab vagrant uname
[localhost] local: vagrant ssh-config
[10.0.3.86:22] Executing task 'uname'
[10.0.3.86:22] run: uname -a
[10.0.3.86:22] out: Linux wheezy 3.8.0-23-generic #34-Ubuntu SMP Wed May 29 20:22:58 UTC 2013 x86_64 GNU/Linux


Done.
Disconnecting from 10.0.3.86... done.