88

我正在寻找一种将参数传递给 Chef 食谱的方法,例如:

$ vagrant up some_parameter

然后some_parameter在其中一本厨师食谱中使用。

4

5 回答 5

119

您不能将任何参数传递给 vagrant。唯一的方法是使用环境变量

MY_VAR='my value' vagrant up

ENV['MY_VAR']在食谱中使用。

于 2013-01-02T15:10:23.243 回答
74

您还可以包含允许您解析命令行选项的GetoptLong Ruby 库。

流浪文件

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 命令之前指定自定义选项,以避免无效选项验证错误。

更多关于图书馆的信息在这里

于 2015-06-26T09:48:39.693 回答
24

可以从 ARGV 读取变量,然后在进入配置阶段之前从中删除它们。修改 ARGV 感觉很恶心,但我找不到任何其他命令行选项的方法。

流浪文件

# 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

 

提供.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
于 2013-11-17T22:33:11.280 回答
8

@benjamin-gauthier 的 GetoptLong 解决方案非常简洁,非常适合 ruby​​ 和 vagrant 范例。

然而,它需要额外的一行来修复对 vagrant 参数的干净处理,例如vagrant destroy -f.

require 'getoptlong'

opts = GetoptLong.new(
  [ '--custom-option', GetoptLong::OPTIONAL_ARGUMENT ]
)

customParameter=''

opts.ordering=(GetoptLong::REQUIRE_ORDER)   ### this line.

opts.each do |opt, arg|
  case opt
    when '--custom-option'
      customParameter=arg
  end
end

这允许此代码块在处理自定义选项时暂停。所以现在, vagrant --custom-option up --provision 还是 vagrant destroy -f 被干净利落地处理了。

希望这可以帮助,

于 2019-03-02T20:41:40.040 回答
2
Vagrant.configure("2") do |config|

    class Username
        def to_s
            print "Virtual machine needs you proxy user and password.\n"
            print "Username: " 
            STDIN.gets.chomp
        end
    end

    class Password
        def to_s
            begin
            system 'stty -echo'
            print "Password: "
            pass = URI.escape(STDIN.gets.chomp)
            ensure
            system 'stty echo'
            end
            pass
        end
    end

    config.vm.provision "shell", env: {"USERNAME" => Username.new, "PASSWORD" => Password.new}, inline: <<-SHELL
        echo username: $USERNAME
        echo password: $PASSWORD
SHELL
    end
end
于 2019-05-28T10:06:20.560 回答