Store Vagrant VM in custom folder

2019-04-21 15:25发布

问题:

I want to specify folder where Vagrant will store my VM.

I need it only for one VM, so I don't want to modify VirtualBox.xml defaultMachineFolder or change VBOX_USER_HOME environment variable.

What is the right way to do it in Vagrantfile?

I've already tried to add the following lines:

config.vm.provider "virtualbox" do |vb|
   vb.customize ["createvm", "--name", "name", "--basefolder", "path"]
end

It creates VM folder on the path I specified, but it also duplicate it in the ~/VirtualBox VMs folder and add the wrong VM path to the VirtualBox.xml.

Also I've tried to use groups:

config.vm.provider :virtualbox do |vb| 
  vb.customize ["modifyvm", :id, "--groups", "/subpath"] 
end

But it only creates a subfolder in the ~/VirtualBox VMs.

Please help!

回答1:

This was not easy but at least I learn a good thing. I will make it as an answer even if you don't find the answer you expected. (sorry in advance)

so first:

It creates VM folder on the path I specified, but it also duplicate it in the ~/VirtualBox VMs folder and add the wrong VM path to the VirtualBox.xml.

yes, by default when you see in the vagrant output something like

==> default: Importing base box 'ubuntu/trusty64'...

behind the scenes, vagrant runs something like VBoxManage import .... so if you also define a createvm property, it will run it in addition to the vagrant box import so it creates duplicate. Note the property set in the provider block does not override the default one but are running after the default one.

so vagrant does VBoxManage import .... --disk /path; when running from VBoxManage, it is easy to change the path specified for disk and save the VM file anywhere.

However when you look the vagrant code here it takes the output of the target path property when running VBoxManage import -n /path_to_your_box_ovf_fileand it builds the path from there so it will be the same path folder for any VM.

so on top of the ways you already mentioned, to define the path you can use the VBoxManage setproperty machinefolder

VBoxManage setproperty machinefolder /my_custom_path
vagrant up
VBoxManage setproperty machinefolder default

the VM files will be creates in your custom_path folder then you reinitialized the VM folder to its default location. (I did not try but as Vagrantfile is a ruby script you could even run the VBoxManage setproperty from the Vagrantfile)