问题
I'm using a simple shell script to provision software for a vagrant setup as seen here.
But can't figure out a way to take the command line arguments passed in to vagrant and send them along to an external shell script. Google reveals that this was added as a feature but I can't find any documentation covering it or examples out there.
回答1:
You're correct. The way to pass arguments is with the :args
parameter.
config.vm.provision :shell, :path => "bootstrap.sh", :args => "'first arg' second"
Note that the single quotes around first arg
are only needed if you want to include spaces as part of the argument passed. That is, the code above is equivalent to typing the following in the terminal:
$ bootstrap.sh 'first arg' second
Where within the script $1 refers to the string "first arg" and $2 refers to the string "second".
The v2 docs on this can be found here: http://docs.vagrantup.com/v2/provisioning/shell.html
回答2:
Indeed, it doesn't work with variables! The correct snytax is :
var1= "192.168.50.4"
var2 = "my_server"
config.vm.provision :shell, :path => 'setup.sh', :args => [var1, var2]
and then, in the shell setup.sh:
echo "### $1 - $2"
> ### 192.168.50.4 - my_server
回答3:
Here is alternative way of passing the variables from the environment:
config.vm.provision "shell" do |s|
s.binary = true # Replace Windows line endings with Unix line endings.
s.inline = %Q(/usr/bin/env \
TRACE=#{ENV['TRACE']} \
VERBOSE=#{ENV['VERBOSE']} \
FORCE=#{ENV['FORCE']} \
bash my_script.sh)
end
Example usage:
TRACE=1 VERBOSE=1 vagrant up
回答4:
For adding explicit arguments, I used this successfully:
config.vm.provision "shell", path: "provision.sh", :args => "--arg1 somearg --arg2 anotherarg"
回答5:
Answering my own question based on some info I found in an old version of the docs page:
config.vm.provision :shell, :path => "bootstrap.sh", :args => "'abc'"
-- @user1391445
回答6:
In new versions You can use array:
config.vm.provision :shell, :path => "bootstrap.sh", :args:["first", "second"]
来源:https://stackoverflow.com/questions/15461898/passing-variable-to-a-shell-script-provisioner-in-vagrant