Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vagrant: How can you run scripts on the host via commands in the guest shell?

It's possible to open ports, network files, and there are plug-ins that allow for running guest or host [shell] commands during Vagrant's Provisioning process.

What I'd like to do is be able to (perhaps through a bash alias) run a command in the Vagrant guest/VM, and have this execute a command on the host, ideally with a variable being passed on the command line.

Example: In my host I run the Atom editor (same applies to TextMate, whatever). If I want to work on a shared file in the VM, I have to manually open that file from over in the host, either by opening it directly in the editor, or running the 'atom filename' shell command.

I want parity, so while inside the VM, I can run 'atom filename', and this will pass the filename to the 'atom $1' script outside of the VM, in the host, and open it in my host editor (Atom).


Note: We use Salt for Vagrant Provisioning, and NFS for mounting, for what it's worth. And of course, ssh with key.

Bonus question: Making this work with .gitconfig as its merge conflict editor (should just work, if the former is possible, right?).

like image 233
rcd Avatar asked Jan 06 '16 18:01

rcd


1 Answers

This is a very interesting use case that I haven't heard before. There isn't a native method of handling this in Vagrant, but this functionality was added to Packer in the form of a local shell provisioner. You could open a GitHub issue on the Vagrant project and propose the same feature. Double check the current list of issues, though, because it's possible someone has beaten you to it.

In the meantime, though, you do have a workaround if you're determined to do this...

  1. Create an ssh key pair on your host.
  2. Use Salt to add the private key in /home/vagrant/.ssh on the box.
  3. Use a shell provisioner to run remote ssh commands on the host from the guest.

These commands would take the form of...

ssh [email protected] "ls -l ~"

In my experience, the 192.168.0.1 IP always points back to the host, but your mileage may vary. I'm not a networking expert by any means.

I hope this works for you and I think a local shell provisioner for Vagrant would be a reasonable feature.

like image 70
Patrick Lee Avatar answered Oct 11 '22 07:10

Patrick Lee