Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Last active May 1, 2024 02:21
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tarnacious/f9674436fff0efeb4bb6585c79a3b9ff to your computer and use it in GitHub Desktop.
Save tarnacious/f9674436fff0efeb4bb6585c79a3b9ff to your computer and use it in GitHub Desktop.
Build a bare bones bootable nixos qcow2 image suitable for running with libvirt/qemu/kvm.

Build a bare bones bootable nixos qcow2 image suitable for running with libvirt/qemu/kvm.

nix-build '<nixpkgs/nixos>' -A config.system.build.qcow2 --arg configuration "{ imports = [ ./build-qcow2.nix ]; }"

Should create a results directory that symlinks to a qcow2 image in the store.

I basically copied this from the openstack image in nixpkgs because I don't know a better way.

Update:

Thanks to @d-goldin I've just learnt I can start a VM using just:

nix-build '<nixpkgs/nixos>' -A vm -I nixos-config=./machine-config.nix build-vm
./result/bin/run-nixos-vm

Which is pretty neat, and I guess pretty common.

{ config, lib, pkgs, ... }:
with lib;
{
imports =
[
<nixpkgs/nixos/modules/installer/cd-dvd/channel.nix>
./machine-config.nix
];
system.build.qcow2 = import <nixpkgs/nixos/lib/make-disk-image.nix> {
inherit lib config;
pkgs = import <nixpkgs> { inherit (pkgs) system; }; # ensure we use the regular qemu-kvm package
diskSize = 8192;
format = "qcow2";
configFile = pkgs.writeText "configuration.nix"
''
{
imports = [ <./machine-config.nix> ];
}
'';
};
}
{ pkgs, lib, ... }:
with lib;
{
imports = [
<nixpkgs/nixos/modules/profiles/qemu-guest.nix>
];
config = {
fileSystems."/" = {
device = "/dev/disk/by-label/nixos";
fsType = "ext4";
autoResize = true;
};
boot.growPartition = true;
boot.kernelParams = [ "console=ttyS0" ];
boot.loader.grub.device = "/dev/vda";
boot.loader.timeout = 0;
users.extraUsers.root.password = "";
};
}
@jtara1
Copy link

jtara1 commented Feb 21, 2024

I was getting file not found error trying to nixos-rebuild dry-build within the VM running the qcow2

because of

    configFile = pkgs.writeText "configuration.nix"
      ''
        {
          imports = [ <./machine-config.nix> ];
        }
      '';

I replaced it with

    configFile = pkgs.writeText "configuration.nix" (pkgs.lib.readFile ./machine-config.nix);

It's really useful to have a qcow2 file. Used gnome boxes to run the qcow2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment