Virt Sparsify

Thursday, Jun 3, 2021
#unix #tool #vm

When using most hypervisors your virtual drives grow indefinitely until they reach their max size as the virtual machine is used. You can check the max size of your virtual drive ls and check the actual used disk space with du.

/var/lib/libvirt/images ls -lh camera.qcow2
-rw------- 1 libvirt libvirt 401G May 27 16:29 camera.qcow2
/var/lib/libvirt/images du -h camera.qcow2
345G    camera.qcow2

This particular virtual machine takes up 345Gb, but if I boot up the virtual machine and check the file manager I’m using far less than that. When files are deleted in a virtual machine data is not freed up on the host. Fortunately, there’s a wonderful tool called virt-sparsify that can be used to shrink the drive. It comes as part of libguestfs which is a c library and collection of simple tools for creating, reading, and modifying virual disk images. It works with the vast majority of hypervisors including VMware, KVM, qemu, VirtualBox, and Xen to name a few. It includes loads of helpful tools, but I probably use it for virt-sparsify most often.

sudo virt-sparsify camera.qcow2 camera-mini.qcow2