How to mount qcow2 image on host's boot?

I have a VM that I use sparsely, and I want to mount the disk image, and manage it via some software to keep files up to date, and then when I do happen to want to boot.

# modprobe nbd max_part=16
# qemu-nbd -c /dev/nbd0 /path/to/image.qcow2
# mount /dev/nbd0p2 mountpoint

I can mount the image manually with the above commands, but doing this automatically with nixos (or even any OS really) seems to be poorly documented.

You can simply write a service that runs those commands:

systemd.services.mount-vm-disk= {
  wantedBy = [ "multi-user.target" ];
  path = [ pkgs.qemu pkgs.kmod ];
  serviceConfig.Type = "oneshot";
  serviceConfig.RemainAfterExit = true;
  script = ''
    modprobe nbd max_part=16
    qemu-nbd -c /dev/nbd0 /path/to/image.qcow2
    mount /dev/nbd0p2 mountpoint
  '';
  preStop = ''
    qemu-nbd -d /dev/nbd0
    rmmod nbd
  '';
};

and then when I do happen to want to boot.

Note that that you should’t boot the VM while the image is mounted, so you must stop the service first.

and manage it via some software to keep files up to date

Why don’t you share a directory using virtio-9p instead? That way you don’t have to physically copy the file into the image.

9p is stupidly slow and not really reliable for gaming off :wink: most games don’t like being run from a network drive.

Thanks for the tip on getting this working.