{ config, lib, pkgs, ... }: with lib; let cfg = config.my.virtualisation.podmanPods; containerDefinition = config.virtualisation.oci-containers.containers.type.getSubOptions; # Add our enable option extendedContainerOptions = containerDefinition // { enable = mkEnableOption "Enable this container"; }; podOptions = { options = with types; { name = mkOption { type = str; description = "Name of the pod"; }; ports = mkOption { type = listOf str; default = [ ]; description = "List of port mappings (e.g. ['8080:80'])"; }; containers = mkOption { type = attrsOf (submodule { options = extendedContainerOptions; }); default = { }; description = "Attribute set of OCI container configurations for this set"; }; }; }; createPodScript = name: podDef: let podDefinitionString = builtins.toJSON { inherit (podDef) ports; }; in pkgs.writeScript "manage-pod-${name}.sh" '' #! /bin/sh set -e POD_NAME="${name}" POD_DEFINITION="${podDefinitionString}" create_pod() { podman pod create --name "$POD_NAME" \ ${concatStringsSep " " (map (port: "--publish ${port}") podDef.ports)} } if podman pod exists "$POD_NAME"; then CURRENT_CONFIG=$(podman pod inspect "$POD_NAME" | jq -c '{ports: .[0].InfraConfig.PortBindings | to_entries | map("\(.value[0].HostPort):\(.key | split("/")[0])") | sort'}) echo "POD_DEFINITION: $POD_DEFINITION" echo "CURRENT_CONFIG: $CURRENT_CONFIG" if [ "$CURRENT_CONFIG" != "$POD_DEFINITION" ]; then echo "Pod configuration has changed. Recreating pod..." podman pod rm -f "$POD_NAME" create_pod else echo "Pod configuration unchanged." fi else echo "Pod does not exist. Creating..." create_pod fi ''; enabledContainers = containers: mapAttrs (name: container: removeAttrs container [ "enable" ]) ( filterAttrs (name: container: container.enable) containers ); in { options.my.virtualisation.podmanPods = mkOption { type = types.attrsOf (types.submodule podOptions); default = { }; description = "Podman pods to create"; }; config = mkIf (cfg != { }) { my.virtualisation.podman.enable = true; environment.systemPackages = [ pkgs.jq ]; networking.firewall.allowedTCPPorts = flatten ( mapAttrsToList ( name: podDef: map (portMapping: lib.toInt (lib.head (lib.splitString ":" portMapping))) podDef.ports ) cfg ); systemd.services = let containers = enabledContainers config.containers; podServices = mapAttrs' ( name: podDef: nameValuePair "podman-pod-${name}" { description = "Manage Podman pod: ${name}"; serviceConfig = { Type = "oneshot"; ExecStart = "${createPodScript name podDef}"; }; path = [ pkgs.jq pkgs.podman ]; after = [ "network.target" ]; wantedBy = [ "multi-user.target" ]; } ) cfg; containerServices = mapAttrs' ( name: container: nameValuePair "podman-${name}" { after = [ "podman-pod-${lib.head (lib.splitString "-" name)}.service" ]; requires = [ "podman-pod-${lib.head (lib.splitString "-" name)}.service" ]; partOf = [ "podman-pod-${lib.head (lib.splitString "-" name)}.service" ]; } ) containers; in podServices // containerServices; }; }