diff --git a/hosts/server7/containers/default.nix b/hosts/server7/containers/default.nix index 71f895fa..976b8a10 100644 --- a/hosts/server7/containers/default.nix +++ b/hosts/server7/containers/default.nix @@ -35,4 +35,11 @@ let in { boot.enableContainers = true; inherit containers; + + imports = [ ../../../lib/lxc ]; + lxc.containers = { + trivial = { + nixos-config = "/tmp/trivial.nix"; + }; + }; } diff --git a/lib/lxc/default.nix b/lib/lxc/default.nix new file mode 100644 index 00000000..a3be7663 --- /dev/null +++ b/lib/lxc/default.nix @@ -0,0 +1,62 @@ +{ config, lib, pkgs, ... }: +with lib; + +let + profilesDir = "/nix/var/nix/profiles/lxc"; + gcRoots = "/nix/var/nix/gcroots/lxc"; + containers = config.lxc.containers; +in { + options = with types; { + lxc.containers = mkOption { + type = attrs; + default = {}; + }; + }; + + config = mkIf (containers != {}) { + virtualisation.lxc = { + enable = true; + }; + + systemd.services = + builtins.foldl' (services: name: + let + config = builtins.getAttr name containers; + builder = { + description = "Build NixOS for lxc container ${name}"; + wants = [ "nix-daemon.socket" ]; + after = [ "nix-daemon.service" ]; + + path = with pkgs; [ coreutils nix ]; + + serviceConfig.Type = "oneshot"; + serviceConfig.RemainAfterExit = true; + + script = '' + mkdir -p ${profilesDir}/${name} + mkdir -p ${gcRoots}/${name} + + nix-env -p ${profilesDir}/${name}/system \ + -I nixos-config=${config.nixos-config} \ + -f '' \ + --set -A system + ''; + }; + starter = { + description = "LXC container ${name}"; + requires = [ "lxc-container-${name}-builder" ]; + after = [ "lxc-container-${name}-builder" ]; + + path = with pkgs; [ lxc ]; + + script = '' + lxc-start -F -n ${name} + ''; + }; + in services // { + "lxc-container-${name}-builder" = builder; + "lxc-container-${name}" = starter; + } + ) {} (builtins.attrNames containers); + }; +}