{ inputs, lib, config, pkgs, ... }: let postgresPasswordPath = lib.optionalString (lib.hasAttr "sops-nix" inputs) config.sops.secrets."software/postgres/postgres/password".path; pubKeys = lib.filesystem.listFilesRecursive ../../users/keys; container_name = "postgres"; container_ip = "10.0.10.5"; in { sops.secrets = { "software/postgres/postgres/password" = { }; }; environment.persistence."/persist" = { hideMounts = true; directories = [ "/var/lib/nixos-containers/${container_name}" ]; }; networking.nat.enable = true; networking.nat.internalInterfaces = ["ve-+"]; networking.nat.externalInterface = "br0"; containers.postgres = { 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 = "10.0.10.1"; interfaces.eth0.ipv4.addresses = [ { "address" = "${container_ip}"; "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"; }; }; }