How to build a standalone NixOS QEMU VM?

EDIT: You’re invited to read the followup to this question here.

Based on the excellent Mayflower article I did some mods (based on @Elyhaka’s idea) reusing the custom-iso.nix the article provides. I plan to modify the expression to output a qcow file instead of an iso file and change the op’s original shell script accordingly with that. Result would be a standalone shell script to create the qcow file usable in qemu.

nix-build --out-link vm - <<'EOF'
{ nixpkgs ? <nixpkgs>, system ? "x86_64-linux", pkgs ? import <nixpkgs/nixos> {}, ... }:
let
  myisoconfig = { pkgs, lib, ... }: with lib; with pkgs; {
    imports = [
      "${nixpkgs}/nixos/modules/profiles/qemu-guest.nix"
      "${nixpkgs}/nixos/modules/installer/cd-dvd/channel.nix"
    ];
  };
  
  evalNixos = config: import "${nixpkgs}/nixos/lib/make-disk-image.nix" {
    inherit (pkgs) lib pkgs config;
    diskSize = 8192;
    format = "qcow2";
    configFile = pkgs.writeText "configuration.nix"
      ''
        {
          # TODO Write text of myisoconfig above here as file
        }
      '';
  };
in { vm = (evalNixos myisoconfig).config.system.build.qcow; }
EOF

Error:

error: file ‘nixos-config’ was not found in the Nix search path (add it using $NIX_PATH or -I), at /home/me/.nix-defexpr/channels/nixpkgs/nixos/default.nix:1:60

What still bothers me is the error message. It is rooted in line 2 (…) import <nixpkgs/nixos> (…) and I just want to use myisoconfig from my expression instead of providing -I nixos-config interactively.

Any pointers welcome!

2 Likes