Skip to content

Instantly share code, notes, and snippets.

@cojocar
Last active August 11, 2022 11:00
Show Gist options
  • Save cojocar/163d2a37f99519ad0a40 to your computer and use it in GitHub Desktop.
Save cojocar/163d2a37f99519ad0a40 to your computer and use it in GitHub Desktop.
Shrink size of a qcow image that contains an OS.

Prepare environment

$ wget https://people.debian.org/~aurel32/qemu/i386/debian_wheezy_i386_standard.qcow2
$ qemu-img info debian_wheezy_i386_standard.qcow2
image: debian_wheezy_i386_standard.qcow2
file format: qcow2
virtual size: 25G (26843545600 bytes)
disk size: 256M
cluster_size: 65536
$ sudo modprobe nbd max_part=16
$ mkdir /tmp/src /tmp/dst

Create the new image and the new file system (2GB size in our case)

$ qemu-img create -f qcow2 debian7_i386.qcow2 2G
Formatting 'debian7_i386.qcow2', fmt=qcow2 size=2147483648 encryption=off cluster_size=65536
# prepare the new image file system
$ sudo qemu-nbd -c /dev/nbd1 debian7_i386.qcow2
$ sudo cfdisk /dev/nbd1
# create msdos partition table
# create ext4 partition (bootable)
# commit and quit
# reconnect to use the new partition table
$ sudo qemu-nbd -d /dev/nbd1
$ sudo qemu-nbd -c /dev/nbd1 debian7_i386.qcow2
$ sudo mkfs.ext4 /dev/nbd1p1

Copy files in the new image

$ sudo qemu-nbd -c /dev/nbd0 debian_wheezy_i386_standard.qcow2
$ sudo mount /dev/nbd0p1 /tmp/src/
$ sudo mount /dev/nbd1p1 /tmp/dst/
$ sudo cp -pRv /tmp/src/* /tmp/dst/
$ sync
# this will take a while
$ sudo umount /tmp/dst /tmp/src
$ sudo qemu-nbd -d /dev/nbd0
$ sudo qemu-nbd -d /dev/nbd1

##Install grub on the new disk

# boot the original image and install grub on the new image
$ qemu-system-i386 -hda debian_wheezy_i386_standard.qcow2 -hdb debian7_i386.qcow2
# inside the VM, install grub
$$ AUUID=$(blkid /dev/sda1 | cut -f2 -d' ' | cut -f2 -d= | tr -d '"')
$$ BUUID=$(blkid /dev/sda1 | cut -f2 -d' ' | cut -f2 -d= | tr -d '"')
$$ mkdir /tmp/mnt
$$ mount /dev/sdb1 /tmp/mnt
$$ sed -i s/${AAUID}/${BUUID}/g /tmp/mnt/boot/grub/grub.cfg
$$ sed -i s/${AAUID}/${BUUID}/g /tmp/mnt/etc/fstab
$$ umount /tmp/mnt
$$ grub-install /dev/sdb
$$ shutdown -h now
# now you should be able to boot the small image
$ qemu-system-i386 -hda debian7_i386.qcow2

Compress the image

$ qemu-img convert -c -f qcow2  -O qcow2 debian7_i386.qcow2 debian7_i386.qcow2.compressed
# the image debian7_i386.qcow2.compressed is ready for upload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment