NixOS base qcow via shell script

In this thread I raised the question how a shell script to generate base nixos install via qcow file would look alike.

It is proof of concept and thus by far not production ready.

Here is what I got:

#! /usr/bin/env nix-shell
#! nix-shell -i bash -p qemu

set -eo pipefail
nix-build --no-out-link vm -I nixpkgs=channel:nixos-19.09-small - <<'EOF'
{ nixpkgs ? <nixpkgs>, config ? <nixos-config>, system ? builtins.currentSystem, pkgs ? import <nixpkgs/nixos> {}, ... }:
let
  evalQcow = { config, lib, pkgs, ... }: import "${toString nixpkgs}/nixos/lib/make-disk-image.nix" {
    inherit lib config pkgs;
    diskSize = 8192;
    format = "qcow2";
  };
  myconfig = { config, lib, pkgs, ... }: {
    imports = [
      "${toString nixpkgs}/nixos/modules/profiles/qemu-guest.nix"
      "${toString nixpkgs}/nixos/modules/installer/cd-dvd/channel.nix"
    ];
    fileSystems."/" = {
      device = "/dev/disk/by-label/nixos";
      autoResize = true;
      fsType = "ext4";
    };
    boot.growPartition = true;
    boot.kernelParams = [ "console=ttyS0" ];
    boot.loader.grub.device = lib.mkDefault "/dev/vda";
    boot.loader.timeout = 0;
    users.extraUsers.root.password = "mynixos";
    system.build.qcow = (evalQcow { inherit config; inherit lib; inherit pkgs; });
  };
  evalNixos = configuration: import "${toString nixpkgs}/nixos/default.nix" {
    inherit system configuration;
  };
  
in { vm = (evalNixos myconfig).config.system.build.qcow; }
EOF

instead of evalNixos

(...)
evalLibConfig = configuration: import "${toString nixpkgs}/nixos/lib/eval-config.nix" {
    inherit system;
    modules = [ configuration ];
  };
(...)

also works.

I pinned the thing to 19.09 due to a kvm-related regression, mentioned i. e. here.

To test it in a WSL (1 actually) environment one can use

$ nix-shell -p qemu --run "nix-shell -p vde2 --run "nix-shell -p spice_gtk""

and therein

$ sudo -i qemu-kvm -drive index=0,id=drive0,file=/nix/store/10ybw0smk9hybrnv520l0k2pjfm2v8vx-nixos-disk-image/nixos.qcow2
2 Likes