Pass command line argument to vagrant shell script provisioner

前端 未结 2 1596
无人共我
无人共我 2021-01-14 10:25

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 va

相关标签:
2条回答
  • 2021-01-14 11:22

    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
    
    0 讨论(0)
  • 2021-01-14 11:25

    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.

    0 讨论(0)
提交回复
热议问题