Fix db init

This commit is contained in:
soraefir
2026-05-06 02:01:25 +02:00
parent e7a414df5f
commit dd192d2983

View File

@@ -23,19 +23,43 @@ in {
backupAll = true; # Backs up all databases and roles
};
systemd.services.postgresql.postStart = lib.mkAfter ''
PSQL="${pkgs.postgresql}/bin/psql"
${lib.concatMapStringsSep "\n" (name: ''
$PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname = '${name}_user'" | grep -q 1 || \
$PSQL -tAc "CREATE ROLE ${name}_user WITH LOGIN;"
# systemd.services.postgresql.postStart = lib.mkAfter ''
# PSQL="${pkgs.postgresql}/bin/psql"
# ${lib.concatMapStringsSep "\n" (name: ''
# $PSQL -tAc "SELECT 1 FROM pg_roles WHERE rolname = '${name}_user'" | grep -q 1 || \
# $PSQL -tAc "CREATE ROLE ${name}_user WITH LOGIN;"
$PSQL -tAc "ALTER DATABASE ${name}_db OWNER TO ${name}_user;"
# $PSQL -tAc "ALTER DATABASE ${name}_db OWNER TO ${name}_user;"
if [ -f "${config.sops.secrets."${name}_pass".path}" ]; then
PASS=$(cat "${config.sops.secrets."${name}_pass".path}")
$PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';"
fi
'') allApps}
'';
# if [ -f "${config.sops.secrets."${name}_pass".path}" ]; then
# PASS=$(cat "${config.sops.secrets."${name}_pass".path}")
# $PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';"
# fi
# '') allApps}
# '';
systemd.services.init-db-permissions = {
description = "Set DB passwords and ownership after Postgres is ready";
after = [ "postgresql.service" ];
requires = [ "postgresql.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
User = "postgres"; # Runs as postgres user directly
RemainAfterExit = true;
};
script = ''
PSQL="${pkgs.postgresql}/bin/psql"
${lib.concatMapStringsSep "\n" (name: ''
$PSQL -tAc "ALTER DATABASE ${name}_db OWNER TO ${name}_user;"
if [ -f "${config.sops.secrets."${name}_pass".path}" ]; then
PASS=$(cat "${config.sops.secrets."${name}_pass".path}")
$PSQL -tAc "ALTER USER ${name}_user WITH PASSWORD '$PASS';"
fi
'') allApps}
'';
};
};
}