Convert a root filesystem to a bootable disk image

The year is 2022, and it is still that complicated to install GRUB2 externally onto a disk image.

But using the wonders of libguestfs, you can create a bootable diskimage using a qemu VM abstraction very easily. The steps here imply we want to create a disk with a single partition containing the root filesystem.

Create an empty disk image, partition it

$ truncate --size 40G target.img
$ virt-format --add target.img --partition=mbr --filesystem=ext4

copy the root file system into a partition

cd path/to/root/fs
sudo tar --numeric-owner -cvf - . | guestfish --rw --add ../target.img --mount /dev/sda1:/ -- tar-in - /

install grub using guestfish

$ guestfish --add target.img --inspector

and in the guestfish prompt:

>> command 'grub-install /dev/sda'
>> command 'update-grub'
# also make sure init can mount our root partition
>> write /etc/fstab '/dev/sda1 / ext4 defaults 0 1'
>> exit

test boot the disk image

$ kvm -m 2048 -drive file=target.img,format=raw