nix.dev has documentation for building NixOS VMs using the handy qemu-vm.nix
module. With a bit of digging into how this works it’s easy enough to adapt How to build a NixOS configuration from a flake with nix build to also build this script from a flake and run your NixOS configuration as a VM.
At the time of writing, the vm
property is set here in nixpkgs/nixos/default.nix
:
{
...
inherit (eval.config.system.build) vm vmWithBootLoader;
}
and that property comes from qemu-vm.nix
here:
system.build.vm =
hostPkgs.runCommand "nixos-vm"
...
hostPkgs.runCommand
creates a derivation which when built will run a shell script, in this case it’s the script which builds the run-nixos-vm
script. So to use it in a flake, have a nixosConfiguration.<host>
property and a configuration.nix
like normal:
{
description = "A very basic flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
};
outputs = { self, nixpkgs }: {
nixosConfigurations.test = nixpkgs.lib.nixosSystem {
system = "x86_64-linux";
modules = [
./configuration.nix
];
};
};
}
and then run (-L for logs
)
nix build -L .#nixosConfigurations.test.config.system.build.vm
QEMU_KERNEL_PARAMS=console=ttyS0 ./result/bin/run-nixos-vm -nographic; reset
Addendum
Ok it turns out you have to explicitly import qemu-vm.nix
for this to work properly and give you all the virtualisation
options, so add:
imports = [
"${modulesPath}/virtualisation/qemu-vm.nix"
];
to configuration.nix
.