Run script on host machine during vagrant up

I'd like to run a bash script on the host machine when vagrant provisions the server.

What would be the best method of achieving this?


Solution 1:

At least two plugins which should help:

  • vagrant-host-shell
  • vagrant-triggers

If you don't care that the script is run on (almost) all vagrant commands, you can also just shell out (or use what ever ruby magic) in Vagrantfile:

system('./myscript.sh')

Vagrant.configure('2') do |config|
  # ...
end

Solution 2:

Simple (and complete) Solution

(I say complete because the accepted answer does not check if the user is using vagrant up. Therefore, the script is executed on each command, which is not what the OP wants.)

There is however a simple solution to this.

ARGV[0] is the first argument of the command entered and can be up, down, status, etc.. Simply check the value of ARGV[0] in your Vagrantfile.


Something like this will do:

system("
    if [ #{ARGV[0]} = 'up' ]; then
        echo 'You are doing vagrant up and can execute your script'
        ./myscript.sh
    fi
")

Vagrant.configure('2') do |config|
  # ...
end