{ inputs, lib, config, configVars, pkgs, ... }: let postgresPasswordPath = lib.optionalString (lib.hasAttr "sops-nix" inputs) config.sops.secrets."software/postgres/postgres/password".path; pubKeys = lib.filesystem.listFilesRecursive ../../users/keys; containerName = "postgres"; containerIp = configVars.networking.addresses.postgres.ip; gatewayIp = configVars.networking.addresses.gateway.ip; in { sops.secrets = { "software/postgres/postgres/password" = { }; }; environment.persistence."/persist" = { hideMounts = true; directories = [ "/var/lib/nixos-containers/${containerName}" ]; }; networking.nat.enable = true; networking.nat.internalInterfaces = ["ve-+"]; networking.nat.externalInterface = "br0"; containers.${containerName} = { autoStart = true; privateNetwork = true; hostBridge = "br0"; nixpkgs = pkgs.path; bindMounts = { "/var/lib/postgresql" = { hostPath = "/media/main-ssd/postgresql"; isReadOnly = false; }; }; config = { pkgs, lib, ... }: { networking = { defaultGateway = "${gatewayIp}"; interfaces.eth0.ipv4.addresses = [ { "address" = "${containerIp}"; "prefixLength" = 24; } ]; firewall = { enable = true; allowedTCPPorts = [ 5432 ]; }; useHostResolvConf = lib.mkForce false; }; services.resolved.enable = true; environment.systemPackages = with pkgs; [ lsof ]; services.postgresql = { enable = true; enableJIT = true; package = pkgs.postgresql_16; extraPlugins = with pkgs.postgresql_16.pkgs; [ postgis ]; settings = { max_worker_processes = "12"; max_parallel_workers = "8"; max_parallel_workers_per_gather = "4"; max_connections = "100"; autovacuum_work_mem = "2GB"; shared_buffers = "32GB"; work_mem = "0.32GB"; maintenance_work_mem = "64MB"; }; authentication = pkgs.lib.mkOverride 10 '' #type database DBuser auth-method local all all trust ''; }; systemd.services.postgresql.postStart = '' $PSQL -tA <<'EOF' DO $$ DECLARE password TEXT; BEGIN password := trim(both from replace(pg_read_file('${postgresPasswordPath}'), E'\n', ''')); EXECUTE format('ALTER ROLE postgres WITH PASSWORD '''%s''';', password); END $$; EOF ''; services.openssh = { enable = true; settings.PasswordAuthentication = false; }; users.users.root = { openssh.authorizedKeys.keys = lib.lists.forEach pubKeys (key: builtins.readFile key); }; system.stateVersion = "24.05"; }; }; }