michael orlitzky

Resizing a KVM or QEMU disk image

posted 2010-03-21

A What or a What

KVM stands for Kernel-based Virtual Machine, and QEMU stands for, uh, Q Emulator? Both are virtualization solutions; KVM is QEMU, but running within the Linux kernel to improve performance.

The most common virtual disk format (for both KVM and QEMU) is called qcow2, and I'm going to assume that you're using it. If not, you can probably adapt the commands to whatever-format-you're-using, but I can't be bothered to check.

The Problem

When you create a virtual disk image, you have to choose both its format and its size. For example,

user $ qemu-img create -f qcow2 example.img 10G

would create a (qcow2) disk image with 10 gigabytes of space.

If you're like me, when you do this, you will literally exclaim some such nonsense as “this is only a testing server, it will never need more than 10 gigs of space.” And, if you're like me, you will be completely wrong. Eventually, you will want to add some extra space to the virtual disk without having to reformat it and start from scratch.

Prior Art

So there are actually a lot of existing references explaining how to do this. They are all completely wrong.

To be fair, the fdisk methods might actually work, but I stop reading when something tells me to calculate heads and cylinders. Good advice in any discipline.

Anyway, my point is, everyone else is an idiot. There is a simple solution that combines the approaches outlined in those articles (and you never type fdisk not even once).

The Real Slim Shady

From now on, we assume your existing VM disk image is called example.img. How much space would you like to add to it? Write this number down, but do so at the end of this command:

user $ qemu-img create -f raw additional.raw <size>

Here, <size> is the amount of space that you want to add. So, 512M for 512 megabytes, 10G for 10 gigabytes and so on. This will create an empty raw image containing as much (empty) space as you'd like to add to the real image.

Now, convert your existing image to raw format as well.

user $ qemu-img convert -f qcow2 example.img -O raw example.raw

And append the raw additional space to the end of your raw image:

user $ cat additional.raw >> example.raw

Finally, convert the whole thing back to qcow2. I'm going to make a copy here instead of overwriting the original. This wastes a lot of disk space temporarily, but is safer if you've got the space to spare.

user $ qemu-img convert -f raw example.raw -O qcow2 example-expanded.img

…and that's it. The example-expanded.img image should contain empty space after the final partition. To resize the partitions, download the GParted LiveCD, and boot it on the VM. You know how to do this; otherwise, you wouldn't be able to install an operating system on your VM.