Reading time: 2 min
I tried to install grub on a loopback device created with kpartx. Did not went well.
grub-install freaks out about /dev/mapper/whatever. The program thinks all files inside /dev/mapper are LVM devices (there is smart, and too smart :(), so we cannot use kpartx.
Define some helper vars:
export DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
export IMG="$DIR/cool-image-name.img"
export DIR_MNT="/mnt/cool-dir"
Create an image file to work with:
rm -rfv "$IMG"
truncate --size 4G "$IMG"
# TODO: use parted
echo "/dev/sda1 : start=2048, size=2097152, type=c, bootable" | sfdisk "$IMG"
Create a fake block device (if not already created), store it’s path in a DEV variable:
export DEV="$(losetup -ln --raw | grep "$DIR" | cut -d" " -f1)"
if [ -z "$DEV" ]; then
export DEV=$(losetup -f)
sudo losetup --show -f -P "$IMG"
fi
losetup created /dev/loopXpY. Store it in a helper variable:
# TODO: do not hardcode p1
export PART="${DEV}p1"
Format partition (if not already formatted):
[ "$(sudo file -sLb "$PART")" = "data" ] && sudo mkfs.vfat -n "RESCUE" "$PART"
Now mount it (if not already mounted):
mountpoint -q "$DIR_MNT" || sudo mount -o uid=v,gid=v "$PART" "$DIR_MNT"
Create a boot directory for grub:
mkdir -pv "$DIR_MNT/boot"
Install grub2 on a loopback device. Grub is not complaining. Partition is /dev/loopXpY not /dev/mapper/loopXpY (kpartx way), so grub is happy. Live and prosper:
sudo grub-install --target=i386-pc --recheck --boot-directory="$DIR_MNT/boot" "$DEV"
Copy some grub config if u want:
cp -v "/tmp/best-dir-ever/grub.cfg" "$DIR_MNT/boot/grub/"
Cleanup:
sudo umount "$DIR_MNT"
sudo losetup -d "$DEV"
Define some helper vars:
export VM="cool-vm-name"
export BCK="$DIR/coolest-backup-file-ever.fsa"
Mount a VM to test grub:
mountpoint -q "$DIR_MNT" && sudo umount "$DIR_MNT"
virsh -c qemu:///system start "$VM"
exec virt-viewer -c qemu:///system "$VM"
Kill that testing VM with:
virsh -c qemu:///system destroy "$VM" --graceful
Backup stuff from VM:
sudo fsarchiver savefs -o "$BCK" /dev/loop0p1 -v -j8