How to run Fabric commands on Vagrant

How do you use Fabric to script commands on Vagrant-managed VMs?

I thought it was as simple as this example , but I cannot get it to work.

The tramp itself works fine. I can run:

vagrant init
vagrant up --provider=libvirt
vagrant ssh


and connecting via ssh is just fine. However, using the Fabric example, if I try to run:

fab vagrant uname


it cannot connect to error:

[] Executing task 'test_dev_env'
[] run: uname -a

Fatal error: Low level socket error connecting to host on port 2222: Connection refused (tried 1 time)

Underlying exception:
    Connection refused



What is causing this error? As far as I know, vagrant ssh

should work with the same ssh command as Fabric. But of course, even if I manually run the ssh command:

ssh -i /myproject/.vagrant/machines/default/libvirt/private_key -p 2222 vagrant@


I also get the error:

ssh: connect to host port 2222: Connection refused


What am I doing wrong?


source to share

2 answers

Apparently the vagrant doesn't actually set port forwarding, so the only way to connect to the VM is to get the IP address from vagrant ssh-config

and then connect to it. So, the correct task of the tarpaulin Fabric looks like this:

def vagrant():
    result = local('vagrant ssh-config', capture=True)

    hostname = re.findall(r'HostName\s+([^\n]+)', result)[0]
    port = re.findall(r'Port\s+([^\n]+)', result)[0]
    env.hosts = ['%s:%s' % (hostname, port)]

    env.user = re.findall(r'User\s+([^\n]+)', result)[0]
    env.key_filename = re.findall(r'IdentityFile\s+([^\n]+)', result)[0]




By default Vagrant seems to send tcp port 22 (ssh) to port 4567 localhost.

Instead, listen on port 2222, enable it in yours Vagrantfile

: "forwarded_port", guest: 22, host: 2222, id: 'ssh'




All Articles