4

Similar to this question: Passing variable to a shell script provisioner in vagrant

I want to pass variables to a shell script provisioner but I want to set these variables on the command line when I call the provisioner. Is this possible?

Community
  • 1
  • 1
mhkeller
  • 713
  • 1
  • 8
  • 19

2 Answers2

6

This is what I would try - I guess there are possibilities as Vagrantfile is a ruby script, you can use most of ruby possibilities

Be careful though as vagrant might need to check for variables, for example when doing vagrant up arg1 arg2, it expects arg1 and arg2 to be machine names defined in Vagrantfile and will raise an error as it cannot find it

So you would need to pass those variables like

vagrant --arg1 --arg2 up

To read them you could

# -*- mode: ruby -*-
# vi: set ft=ruby :

v1 = ARGV[0]
v2 = ARGV[1]
array_arg = [v1, v2]


Vagrant.configure("2") do |config|

  blabla config

  array_arg.each do |arg|
    config.vm.provision "shell", run: "always" do |s|
      s.inline = "echo $1"
      s.args   = arg
    end
  end
end

for example, the execution would give

fhenri@machine:~/project$ vagrant --arg1 --arg2 up
    . . . . . 
==> default: Running provisioner: shell...
    default: Running: inline script
==> default: stdin: is not a tty
==> default: --arg1
==> default: Running provisioner: shell...
    default: Running: inline script
==> default: stdin: is not a tty
==> default: --arg2
Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • I'd like to call `vagrant provision --arg1` such that it doesn't run `vagrant up` but rather `vagrant provision` (in case the machine is up but needs reprovisioning) – Jonathan Jun 23 '17 at 01:16
  • if you want to have your own variable you should have then right after `vagrant` command, if you put it after the vagrant command like the provision command, vagrant would expect its a parameter for its own command and will claim there's an error. If you run `vagrant --arg1 provision` in this case it will still run the provision only – Frederic Henri Jun 23 '17 at 08:51
0

In your Vagrantfile, add the following -

{
    "PROVISION_PARAMS" => "some_default_values",
}.each { |key, value| ENV[key] = value if ENV[key] == nil }
  

These arguments can now be passed to shell script provisioner in the following way -

config.vm.provision :shell, privileged: true, run: "always",
                            :path => "../../scripts/script.ps1", 
                            :args => ENV['PROVISION_PARAMS']

You can now provide command line arguments to this script in the following manner -

$ PROVISION_PARAMS=' param1 param2 "param 3" ' vagrant provision

And the script will take default values if these parameters are not specified.

Vandana Sharma
  • 126
  • 1
  • 7