Search code examples
rubyshellvagrantprovisioning

Pass command line argument to vagrant shell script provisioner


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?


Solution

  • 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