Skip to content

Instantly share code, notes, and snippets.

@AoJ
Forked from tarnacious/build-qcow2.nix
Created September 28, 2022 08:52
Show Gist options
  • Save AoJ/39301cc04a00b398a8f9d702368be4c1 to your computer and use it in GitHub Desktop.
Save AoJ/39301cc04a00b398a8f9d702368be4c1 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 = "";
};
}
@AoJ
Copy link
Author

AoJ commented Oct 4, 2022

virt-install                                                \
    --connect qemu:///system                                \
    --name nixos                                            \
    --vcpus 1                                               \
    --memory 2048                                           \
    --autostart                                             \
    --memballoon virtio                                     \
    --network default                                       \
    --boot hd                                               \
    --disk "vol=vm/nixos.qcow2,format=qcow2,bus=virtio"     \
    --noautoconsole                                         \
    --graphics none                                         \
    --os-variant centos8                                    \
    --console pty,target_type=serial                        \
    --machine q35

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