Vagrant Tricks: Add extra disk to box

On the other day someone asked me how to add extra disks to an existing vagrant box using the VirtualBox provider.

Well we all know that VirtualBox as an utility called VBoxManage which allows us to do a lot of actions on our existing virtualbox virtual machine and in fact Vagrant explores this utility a lot when it needs to specify all the vm settings (like for example specify network addresses, and so on).

If we search a little bit the Vagrant doc we’ll find that we can use that utility in a quite easy way:

config.vm.provider "virtualbox" do |v|
  v.customize ["modifyvm", :id, "--cpuexecutioncap", "50"]
end

On this specific setting we are telling virtualbox to update the cpuexecutioncap to 50, pretty easy right?

So let’s do our task.
We want to create a 10GB disk, so we’ll need to the the following action:

$ VBoxManage createmedium disk --filename mydisk.vmdk --format vmdk \
--size 10240

Next attach the newly created disk to the existing controller:

$ VBoxManage storageattach myvm --storagectl IDE Controller \
--port 1 --device 0 --type hdd --medium mydisk.vmdk

Let’s transform these commands to v.costumize actions:

config.vm.provider "virtualbox" do |v|
      v.name = "myvm"
      v.memory = 2048
      v.cpus = 2
      
      v.customize [ "createmedium", "disk", "--filename", "mydisk.vmdk", 
"--format", "vmdk", "--size", 1024 * 10 ]
      v.customize [ "storageattach", "myvm" , "--storagectl", 
"IDE Controller", "--port", "1", "--device", "0", "--type", 
"hdd", "--medium", "mydisk.vmdk"]
end

In order to avoid errors if the vmdk file exists (created by the createmedium task) We’ll need to add a small check condition before creating it:

file_to_disk = "mydisk.vmdk"
unless File.exist?(file_to_disk)
   v.customize [ "createmedium", "disk", "--filename", "mydisk.vmdk", 
"--format", "vmdk", "--size", 1024 * 10 ]
end
v.customize [ "storageattach", "myvm" , "--storagectl", 
"IDE Controller", "--port", "1", "--device", "0", "--type", 
"hdd", "--medium", file_to_disk]

The end 🙂

2 thoughts on “Vagrant Tricks: Add extra disk to box

    1. You can always add extra provisioning script on your vagrantfile to do what you want

      Like

Leave a comment