Mounting or Resizing a VirtualBox VDI Virtual Hard Drive

I previously wrote an entry that included instructions on how to resize a VirtualBox VDI virtual hard drive file. I found a somewhat better method (URL in the Bibliography below) that I'll detail here.

Resizing the virtual HD is easy ... the problem is that the installed OS doesn't detect or use that added space, so the main job is resizing the installed OS partition. The easy part comes first:

$ VBoxManage modifyhd YOUR_HARD_DISK.vdi --resize <SIZE_IN_MB>

I find I'm often using this to resize the OpenWRT VirtualBox images, because when you start tinkering that 50MB limit seems awfully small. You now need to resize the partition(s) in the VDI. The easiest tool for this is gparted, but you won't be running that from OpenWRT. Even if you're resizing a better equipped Linux distribution that has gparted, you can't resize the active boot partition. Last time, I attached the VDI to another Linux virtual machine and used it to make the changes, but couldn't you do it from the host machine? The answer is yes. The tool you need is qemu-nbd, which on Ubuntu is a part of the qemu-utils package. Once it's installed, most of the rest of this must be done as root.

# modprobe nbd
# qemu-nbd -c /dev/nbd0 /home/giles/VirtualBox\ VMs/OpenWRTCCx86/openwrt-cc-x86.vdi
# fdisk -l /dev/nbd0
Disk /dev/nbd0: 200 MiB, 209715200 bytes, 409600 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x076b2e55

Device      Boot Start    End Sectors   Size Id Type
/dev/nbd0p1 *      512   8703    8192     4M 83 Linux
/dev/nbd0p2       9216 409599  400384 195.5M 83 Linux

The web page I copied from had one particularly memorable quote: "Basically, [qemu-nbd] knows all about weird disk image formats, and presents them to the kernel via nbd, and ultimately to the rest of the system as if they were a normal disk." At this point, you can mount and use those partitions like any other. Or, in my case, point gparted at it. When you're done, umount any mounted partitions and remove the block device:

# qemu-nbd -d /dev/nbd0