Files
nixconfig/modules/server/database/default.nix
2026-05-06 03:20:11 +02:00

52 lines
2.1 KiB
Nix

{ config, lib, pkgs, ... }:
let
listNames = config.syscfg.server.db;
containerNames = lib.mapAttrsToList
(name: cfg: name)
(lib.filterAttrs (name: cfg: cfg.db or false) config.syscfg.server.containers);
allApps = lib.unique (listNames ++ containerNames);
in {
config = lib.mkIf ( builtins.length allApps > 0) {
services.postgresql = {
enable = true;
enableTCPIP = true; # Required to listen on network interfaces
authentication = pkgs.lib.mkOverride 10 ''
# TYPE DATABASE USER ADDRESS METHOD
local all all trust
host all all 127.0.0.1/32 trust
host all all 10.0.0.0/8 scram-sha-256
host all all 169.254.0.0/16 scram-sha-256
host all all ::1/128 trust
'';
ensureDatabases = map (name: "${name}_db") allApps;
ensureUsers = map (name: { name = "${name}_user"; }) allApps;
};
services.postgresqlBackup = {
enable = true;
location = "/var/lib/postgresql/backups";
startAt = "*-*-* 04:00:00"; # Runs every day at 4 AM
backupAll = true; # Backs up all databases and roles
};
systemd.services.postgresql.postStart = lib.mkAfter ''
${pkgs.coreutils}/bin/sleep 2
PSQL="${pkgs.postgresql}/bin/psql"
${lib.concatMapStringsSep "\n" (name: ''
until $PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname = '${name}_user'" | grep -q 1; do
echo "Waiting for user ${name}_user..."
sleep 1
done
$PSQL -tAc "ALTER DATABASE ${name}_db OWNER TO ${name}_user;"
if [ -f "${config.sops.secrets."${lib.toUpper name}".path}" ]; then
PASS=$(grep "^DB_PASSWORD=" "${config.sops.secrets."${lib.toUpper name}".path}" | cut -d'=' -f2-)
$PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';"
fi
'') allApps}
'';
};
}