NixOSConfig/lib/config/custom-build-vm.nix

101 lines
3 KiB
Nix
Raw Normal View History

2024-04-30 22:27:07 +00:00
{ config, lib, options, pkgs, ... }: {
options = {
virtualisation = {
runAsRoot = lib.mkOption {
type = lib.types.bool;
default = false;
};
2024-04-30 22:50:02 +00:00
sharedHostKeys = lib.mkOption {
type = lib.types.bool;
default = false;
};
2024-04-30 22:50:02 +00:00
qemu.runInBackground = lib.mkOption {
type = lib.types.bool;
default = false;
};
};
2024-04-30 22:27:07 +00:00
};
2024-04-30 22:27:07 +00:00
config = {
2024-04-30 22:40:00 +00:00
virtualisation =
let
extendVMConfig =
vmVariant: {
boot.loader.efi.efiSysMountPoint = lib.mkVMOverride "/boot";
virtualisation.sharedDirectories = lib.optionalAttrs (vmVariant.virtualisation.sharedHostKeys) {
hostKeys =
let
path = "/etc/ssh";
in {
source = path;
target = path;
};
};
};
virtualisation = config.virtualisation;
2024-04-30 22:40:00 +00:00
in {
vmVariant = extendVMConfig virtualisation.vmVariant;
vmVariantWithBootLoader = extendVMConfig virtualisation.vmVariantWithBootLoader;
runAsRoot = lib.mkIf config.virtualisation.sharedHostKeys true;
2024-04-30 22:40:00 +00:00
};
2024-04-30 22:27:07 +00:00
# Replace native `qemu` with `remote-viewer`
system.build =
{
vm =
let
packageName = "custom-nixos-vm";
2024-04-30 22:27:07 +00:00
mergedSystem =
with options.system;
lib.mergeDefinitions
build.loc
build.type
(lib.lists.forEach
(
builtins.filter
(item:
!(lib.path.hasPrefix ./. (/. + item.file)))
build.definitionsWithLocations)
(item: { inherit (item) file value; }));
in
lib.mkForce (
2024-04-30 22:43:41 +00:00
with { inherit (mergedSystem.mergedValue) vm; };
if (vm.name == packageName)
then
vm
else
let
2024-04-30 22:50:02 +00:00
prefix =
lib.concatStringsSep " " (
lib.optionals config.virtualisation.runAsRoot (
["sudo"] ++
lib.optional config.virtualisation.qemu.runInBackground "-b"));
suffix =
lib.concatStringsSep " " (
lib.optional
(!config.virtualisation.runAsRoot && config.virtualisation.qemu.runInBackground)
"&");
2024-04-30 22:43:41 +00:00
wrapped = pkgs.writeShellApplication {
name = "run-${config.system.name}-vm";
text = ''
2024-04-30 22:50:02 +00:00
${prefix} ${vm}/bin/run-${config.system.name}-vm ${suffix}
2024-04-30 22:43:41 +00:00
'';
};
in
# Rename package to `nixos-vm`
pkgs.symlinkJoin {
name = packageName;
paths = [ wrapped ];
});
2024-04-30 22:27:07 +00:00
};
};
}