The other day, our virtual machine's hard drive filled up. We wanted to grow the hard drive to accommodate more room.  However, it wasn't very easy for us. My coworker Mike, who's absolutely brilliant, came up with a solution so I thought I'd share it here.

A little background: we're running Ubuntu 12.04 LTS and KVM using qcow2 disk images.

The virtual disk image we're trying to resize is called GitLab.qcow2.

Prerequisites

  • Power off the VM.
  • Make a backup.

See the partitions and their sizes

root@titan:/var/vms# virt-df -h GitLab.qcow2 
W: kvm binary is deprecated,
please use qemu-system-x86_64 instead
Filesystem                                Size       Used  Available  Use%
GitLab.qcow2:/dev/sda1                    228M        50M       165M   23%
GitLab.qcow2:/dev/ubuntu/root             7.0G       6.6G        30M   95%

 

Create a new qcow2 file of the desired size.

qemu-img create -f qcow2 GitLabBig.qcow2 40G

virt-resize --expand /dev/sda2 GitLab.qcow2 GitLabBig.qcow2

Move the cows

  • Rename GitLab.qcow2 to GitLabORIG.qcow2
  • Rename GitLabBig.qcow2 to GitLab.qcow2 (the filename expected by virt-manager).
  • Ensure that the permissions are setup correctly (“chown” otherwise).

 

Use gparted to resize the partition.

1.) boot from a gparted ISO (change the boot order of the devices is easiest)

2.) “Unlock” the LVM partition and resize it to fill up the new space.

Use “guestfish” to handle the LVM resizing.

root@titan:/var/vms# guestfish --rw -a GitLab.qcow2
Welcome to guestfish, the libguestfs filesystem interactive shell for
editing virtual machine filesystems.
 
Type: 'help' for help on commands
     'man' to read the manual
     'quit' to quit the shell
 
><fs> run
W: kvm binary is deprecated, please use qemu-system-x86_64 instead
><fs> list-filesystems
/dev/vda1: ext2
/dev/vda2: unknown
/dev/ubuntu/root: ext4
/dev/ubuntu/swap_1: swap
><fs> lvresize-free /dev/ubuntu/root 100
><fs> resize2fs /dev/ubuntu/root
><fs> e2fsck-f /dev/ubuntu/root
><fs> exit
 
root@titan:/var/vms# virt-df -h GitLab.qcow2
W: kvm binary is deprecated, please use qemu-system-x86_64 instead
Filesystem                                Size       Used  Available  Use%
GitLab.qcow2:/dev/sda1                    228M        50M       165M   23%
GitLab.qcow2:/dev/ubuntu/root              39G       6.6G        30G   18%
 

Verify/Cleanup

  • Ensure that things are working as expected.
  • Remove the old backups as appropriate.

 Celebrate!