我正在寻找一种将参数传递给 Chef 食谱的方法,例如:
$ vagrant up some_parameter
然后some_parameter
在其中一本厨师食谱中使用。
我正在寻找一种将参数传递给 Chef 食谱的方法,例如:
$ vagrant up some_parameter
然后some_parameter
在其中一本厨师食谱中使用。
您不能将任何参数传递给 vagrant。唯一的方法是使用环境变量
MY_VAR='my value' vagrant up
并ENV['MY_VAR']
在食谱中使用。
您还可以包含允许您解析命令行选项的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 命令之前指定自定义选项,以避免无效选项验证错误。
更多关于图书馆的信息在这里。
可以从 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
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
@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
被干净利落地处理了。
希望这可以帮助,
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