I needed to expand the root partition in a KVM virtual on a debian host server that has KVM and Libvirt install. The virtual disk that this KVM is using has 2 partitions:
Device Boot Start End Blocks Id System /dev/vda1 63 1060289 530113+ 82 Linux swap / Solaris /dev/vda2 1060290 209715199 104327455 83 Linux
That is the root partition (vda2) is after the swap partition.
Note: All the steps below are done at the Host level
Expand the LVM Partition
The virtual disk vda is actually a LVM Partition on the host machine. It is very easy to expand the Logical volume:
lvresize -L +20G /dev/mapper/kvm-virtual
Expand the LVM virtual in pool kvm by 20Gb
Resize the block device
But this expansion does not expand the block device - so as far as the virtual is concern - the disk is still 20G smaller. So..
virsh blockresize --path /dev/kvm/virtual --size xxG vID
Where vID is the ID of the KVM (e.g. virtual) and xxG is the new size of the virtual disk
Resize the virtual root primary partition
We now need to resize the root primary partition (/dev/vda2 above) to take the free space. We really need to do this with the virtual not running (i.e. /dev/vda2 not mounted). We could run the virtual with a recue CD image to do this but it can be done entirely in the host.So we need to stop the virtual (virsh shutdown vID)
Make the virtual disk structure visible in the host
We need to make the virtual disk structure visible at the host level. To do this, we use kpartx
kpartx -a /dev/kvm/virtual
This will mapped the LV partition virtual to /dev/mapper:e.g.
kvm-virtual kvm-virtualp1 kvm-virtualp2
Edit the virtual disk using a partition editor
Use a partition editor to resize the root partition. All I had was fdisk - so that what I used:
fdisk /dev/mapper/kvm-virtual
Fdisk does not have a partition resizer. So what you need to do is delete the partition and recreate it. Some other editors has a resize function
Notes:
- you need to make sure that the start sector is the same in the old and new partition (The default value may not be)
- You can only easily expand the last partion
- When you exit the editor - you need to refresh the partitions using kpartx so that the host knows the changes:
kpartx -uv /dev/kvm/virtual
Resize the filesystem
You now need to resize the filesystem. In my case, the filesystem was ext4 so I did the following
e2fsck -f /dev/mapper/kvm-virtualp2
resizefs /dev/mapper/kvm-virtualp2
Start the virtual
We now need to remove the partition information on the host:
kpartx -dv /dev/kvm/virtual
We are now ready to start the virtual
virsh start virtual