Files
nixconfig/modules/server/database/default.nix
2026-05-06 22:48:09 +02:00

76 lines
2.6 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
settings = {
listen_addresses = lib.mkForce "*";
};
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 ::1/128 trust
host all all 10.0.0.0/8 scram-sha-256
host all all 169.254.0.0/16 scram-sha-256
'';
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
};
services.redis.servers."main" = {
enable = true;
port = 6379;
bind = "*";
settings.protected-mode = "no";
};
systemd.services.postgresql-init = {
description = "Custom Postgres Setup (Ownership & Passwords)";
after = [ "postgresql.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
User = "postgres";
RemainAfterExit = true;
};
script = ''
${pkgs.coreutils}/bin/sleep 2
PSQL="${pkgs.postgresql}/bin/psql"
${lib.concatMapStringsSep "\n" (name: ''
$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-)
echo $PASS
if $PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';" ; then
echo " Successfully set password for ${name}_user"
else
echo " FAILED to set password for ${name}_user"
fi
fi
'') allApps}
'';
};
};
}