Mounting a VDI File in Ubuntu

Attaching a VDI file to your system as a block device and mounting its partitions (if any).

What I used to do:

  • Create a temporary virtual machine.
  • Add the VDI file to the machine as a HDD.
  • Boot the VM using a live cd.
  • Do whatever I wanted to mount the file for.

It works, but it’s too much hassle. Booting, reserving memory and CPU for the VM and having sub-optimal performance due to the virtualization. So, I looked for another solution and found one here:

Mount a VirtualBox drive image (vdi)

Thanks to Maxime R., I don’t have to go through this hassle again. Instead, we’ll be attaching it as a Network Block Device using QEMU utilities:

sudo apt-get install qemu-utils

If module nbd is already loaded, unload it:

sudo rmmod nbd

then load it again:

sudo modprobe nbd max_part=8

max_part is the maximum number of partitions each block device is allowed to handle. Feel free to alter this value (I’ve seen people doing up to 64). Note that, this value has nothing to do with the 16 nbd block devices that will automatically appear after you load the module.

Then attach the block device to nbd0:

sudo qemu-nbd -c /dev/nbd0 drive.vdi

Now, your block device is attached to /dev/nbd0. Several /dev/nbd0p* partition device nodes should also appear (the partitions within the block device). You can then mount them individually:

sudo mount /dev/nbd0p1 /mnt

Once you are done, unmount everything, disconnect the device and unload the nbd module:

sudo umount /dev/nbd0p1
sudo qemu-nbd -d /dev/nbd0
sudo rmmod nbd

That’s it! I hope this was useful.

Leave a Reply

Your email address will not be published. Required fields are marked *