How to resize kvm raw image with GPT partitions
I am running several VMs with kvm. After a little while I noticed that I was a little to stingy with the amount of space assigned to each VM.
These are the steps I used to reassign more space to the VMs:
- Stop the VM
- Make a backup!
- Get the difference between the size at the moment and the wished size (in my case 4 GiB)
- Create a image with this size consisting of zeros
# copy 4096 times 1 MB of zeros into raw.img dd if=/dev/zero of=raw.img bs=1M count=4096
- Join the image and the zeros into a new file:
cat vm.img raw.img > new_vm.img
- Get the starting sector of the partition and delete the partition
gdisk new_vm.img p (remember the starting sector!) d (use the number of the partition) w (write changes to disk, let gdisk correct the GPT header which is not at the end)
- Recreate the partition
gdisk new_vm.img n (use the number and the first sector from above) [you might want to set the attributes (like bootable) as well] w
- Start the VM and then on (in) the VM and run fsck on the partition
fsck /dev/mypartition # or for root fs: touch /forcefsck && reboot
- Grow the partition inside the VM
resize2fs /dev/mypartition
Update 2017-08-15
It is possible to use sparse files for the update as well:
# create sparse file
truncate -s 16G new_vm.img
# copy old image
dd if=vm.img of=new_vm.img conv=notrunc
Then continue with deleting and recreating the partition you want to resize.