Skip to content

Instantly share code, notes, and snippets.

@Nekroze
Last active April 3, 2022 05:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Nekroze/cbf2c344bd23a6142e176321a1a1ccf5 to your computer and use it in GitHub Desktop.
Save Nekroze/cbf2c344bd23a6142e176321a1a1ccf5 to your computer and use it in GitHub Desktop.
NixOS Declarative KVM Guests
## Builder for NixOS configurations defined at the end of the file to be built into KVM VM's
{ system ? builtins.currentSystem }:
let
loadcfg = cfgfile: { config, pkgs, ...}: {
imports = [ <nixos/modules/virtualisation/qemu-vm.nix> cfgfile ];
config = {
networking.extraHosts = ''
176.32.0.254 template
'';
networking.nameservers = [ "10.50.253.1" "10.51.0.1" "10.51.0.2" "8.8.8.8" ];
networking.defaultGateway = "176.32.0.1";
networking.enableIPv6 = false;
networking.useDHCP = false;
virtualisation = {
graphics = false;
};
};
};
mkcfg = cfgfile:
import <nixos/lib/eval-config.nix> {
inherit system;
modules = [ (loadcfg cfgfile) ];
};
in {
template = (mkcfg ./template.nix).config.system.build.vm;
}
## Declarative configuration of the template KVM guest
{ config, pkgs, ... }:
{
networking.hostName = "template";
networking.firewall.allowedTCPPorts = [ 22 ];
networking.interfaces.eth0 = {
ipAddress = "176.32.0.254";
prefixLength = 24;
};
environment.systemPackages = with pkgs; [ wget ];
virtualisation = {
memorySize = 512;
qemu.networkingOptions = [ "-net nic,macaddr=52:54:00:12:34:01" "-net vde,sock=/run/vde.ctl" ];
};
}
## Triggers the build of KVM VM's specified into systemd services
## Import this into your servers /etc/nixos/configuration.nix
{ config, pkgs, ... }:
let
## Global settings
KVM-GUESTS = "/KVM/guests";
## Triggers a guest build and allows the usage of these VM's as services
KVM-GUESTS-template = ((import ./kvm.nix) {}).template;
in {
## Definitions for running each VM as a service.
systemd.services."kvm-template" = {
description = "KVM NixOS Guest - Template Test Setup";
enable = true;
wantedBy = [ "multi-user.target" ];
environment = {
KVM_NAME = "template";
};
script = ''
VM_STORAGE=${KVM-GUESTS}/$KVM_NAME
mkdir -p $VM_STORAGE
cd $VM_STORAGE
${KVM-GUESTS-template}/bin/run-$KVM_NAME-vm
'';
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment