如何通过“vagrant up”参数并将其放在Vagrantfile的范围内?

我正在寻找一种方法来传递参数给厨师食谱,如:

$ vagrant up some_parameter 

然后在其中一个厨师菜谱中使用some_parameter

你不能通过任何参数stream浪。 唯一的方法是使用环境variables

 MY_VAR='my value' vagrant up 

在配方中使用ENV['MY_VAR']

你也可以包含GetoptLong Ruby库,允许你parsing命令行选项。

Vagrantfile

 require 'getoptlong' opts = GetoptLong.new( [ '--custom-option', GetoptLong::OPTIONAL_ARGUMENT ] ) customParameter='' opts.each do |opt, arg| case opt when '--custom-option' customParameter=arg end end Vagrant.configure("2") do |config| ... config.vm.provision :shell do |s| s.args = "#{customParameter}" end end 

然后,你可以运行:

 $ vagrant --custom-option=option up $ vagrant --custom-option=option provision 

注意:确保在vagrant命令之前指定了自定义选项,以避免无效的选项validation错误。

有关这里的图书馆的更多信息。

在进行configuration阶段之前,可以从ARGV读取variables,然后从中删除variables。 修改ARGV感觉很难受,但我找不到任何其他的命令行选项。

Vagrantfile

 # Parse options options = {} options[:port_guest] = ARGV[1] || 8080 options[:port_host] = ARGV[2] || 8080 options[:port_guest] = Integer(options[:port_guest]) options[:port_host] = Integer(options[:port_host]) ARGV.delete_at(1) ARGV.delete_at(1) Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Create a forwarded port mapping for web server config.vm.network :forwarded_port, guest: options[:port_guest], host: options[:port_host] # Run shell provisioner config.vm.provision :shell, :path => "provision.sh", :args => "-g" + options[:port_guest].to_s + " -h" + options[:port_host].to_s 

provision.sh

 port_guest=8080 port_host=8080 while getopts ":g:h:" opt; do case "$opt" in g) port_guest="$OPTARG" ;; h) port_host="$OPTARG" ;; esac done