Pass environment variables to vagrant shell provisioner

It looks like passing environment variables when calling vagrant up is simple if you're using a Ruby provisioner:

VAR=123 vagrant up

In the Vagrantfile:

ENV['VAR']

How do I do this with the :shell provisioner? Simply doing this does not seem to work:

$VAR

Solution 1:

Since Vagrant 1.8.0 you can forget the ugly hacks from the other answers here. Just use the env option for the shell provisioner (docs).

Use it like this in your Vagrantfile:

config.vm.provision "shell", path: "provisionscript.sh", env: {"MYVAR" => "value"}

This will set the environment for the provisioning script only. If you need a persistent environment variable set for all processes in the VM, this is out of scope for Vagrant provisioning and look here: Shell environment variables in vagrant files are only passed on first up.

Solution 2:

It's not ideal, but I got this to work for now:

config.vm.provision "shell" do |s|
    s.inline = "VAR1 is $1 and VAR2 is $2"
    s.args   = "#{ENV['VAR1']} #{ENV['VAR2']}"
end