How to make sure qemu-img resize does not lose data

kvm-virtualizationqemu

I'm trying to understand how qemu-img resize shrinks the virtual disk. Let's say qemu-img info shows that the virtual size is 20G, and the disk size is only 1G. Now I want to shrink the disk from 20G to a 5G. From the qemu-img documentation here: http://linux.die.net/man/1/qemu-img. It seems I should do it like this :

qemu-img resize filename -15G

But how can I make sure only the empty part of the disk will be shrunk, and my data will not be truncated?

Best Answer

If disk is partitioned, as you indicated, the steps should be (in that order):

  1. shrink filesystem, using OS tools;
  2. shrink partition to the size of the filesystem, you may need to delete it and recreate with the same starting sector;
  3. shrink image to the size of the partition.

The above assumes there's just one partition, if there's more things may be more complicated. The other possible problem are images of format other than raw, as physical size on host may differ from virtual disk size in VM.

Obviously, testing the above procedure on a copy of the image won't hurt. :-)