kenorb kenorb - 3 months ago 37
Ruby Question

How to implement custom option for Vagrant without having invalid option warning?

I'm trying to implement new custom option for Vagrant as in the following

Vagrantfile
:

# -*- mode: ruby -*-
require 'getoptlong'

opts = GetoptLong.new(
[ '--vm-name', GetoptLong::OPTIONAL_ARGUMENT ],
)

vm_name = ENV['VM_NAME'] || 'default'

begin
opts.each do |opt, arg|
case opt
when '--vm-name'; vm_name = arg
end
end
rescue
# @fixme: An invalid option error happens here.
end

Vagrant.configure(2) do |config|
config.vm.define vm_name
config.vm.provider "virtualbox" do |vbox, override|
override.vm.box = "ubuntu/wily64"
end
end


Now, each time when I run any vagrant command it's showing the following warning, e.g.

vagrant destroy -f



/opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant: invalid option -- f


Another example:

$ vagrant --vm-name=foo up --no-provision
/opt/vagrant/embedded/gems/gems/vagrant-1.8.1/bin/vagrant: unrecognized option `--no-provision'
Bringing machine 'foo' up with 'virtualbox' provider...
==> foo: Importing base box 'ubuntu/wily64'...


Is there any way that I can ignore such warning from happening in the above
rescue
section?




This post is similar, but it doesn't help much in this case.

Answer

It's impossible to do this in Vagrantfile. Vagrant parses options before loading Vagrantfile. The moment Vagrantfile is executed, Vagrant process is already in the ensure block after the exception that occurred because of the custom option in the command line. There is nothing one can do in Vagrantfile to recover from that.