self-hosting/modules/postgresql.nix

67 lines
2.2 KiB
Nix
Raw Normal View History

2021-07-15 17:09:32 +02:00
{ config, lib, pkgs, ... }:
{
2021-11-29 02:04:29 +01:00
2021-07-15 17:09:32 +02:00
services.postgresql = {
enable = true;
package = pkgs.postgresql_12;
2021-11-29 02:04:29 +01:00
initialScript = pkgs.writeText "postgres-init.sql" ''
CREATE ROLE "synapse";
CREATE ROLE "nextcloud";
'';
2021-07-15 17:09:32 +02:00
enableTCPIP = true;
2021-07-15 23:46:01 +02:00
identMap = ''
2021-07-17 00:24:30 +02:00
root_as_others root postgres
2021-07-16 03:09:29 +02:00
root_as_others root synapse
2021-07-17 00:24:30 +02:00
root_as_others root nextcloud
2021-07-15 23:46:01 +02:00
'';
2021-07-15 17:09:32 +02:00
authentication = ''
2021-07-15 23:46:01 +02:00
local all postgres peer
local all all peer map=root_as_others
host all all 10.0.1.0/24 md5
2021-07-15 17:09:32 +02:00
'';
};
2021-11-29 02:04:29 +01:00
sops.secrets = {
synapseDbPassword = {
owner = config.services.postgresql.superUser;
key = "synapse/db_password";
restartUnits = [ "postgresql-setup.service" ];
};
nextcloudDbPassword = {
owner = config.services.postgresql.superUser;
key = "nextcloud/db_password";
restartUnits = [ "postgresql-setup.service" ];
};
};
systemd.services.postgresql-setup = let pgsql = config.services.postgresql; in
{
after = [ "postgresql.service" ];
bindsTo = [ "postgresql.service" ];
wantedBy = [ "postgresql.service" ];
path = [
pgsql.package
pkgs.util-linux
];
script = ''
set -eu
PSQL() {
psql --port=${toString pgsql.port} "$@"
}
PSQL -tAc "SELECT 1 FROM pg_database WHERE datname = 'synapse'" | grep -q 1 || PSQL -tAc 'CREATE DATABASE "synapse" OWNER "synapse" TEMPLATE template0 LC_COLLATE = "C" LC_CTYPE = "C"'
PSQL -tAc "SELECT 1 FROM pg_database WHERE datname = 'nextcloud'" | grep -q 1 || PSQL -tAc 'CREATE DATABASE "nextcloud" OWNER "nextcloud"'
synapse_password="$(<'${config.sops.secrets.synapseDbPassword.path}')"
PSQL -tAc "ALTER ROLE synapse WITH PASSWORD '$synapse_password'"
nextcloud_password="$(<'${config.sops.secrets.nextcloudDbPassword.path}')"
PSQL -tAc "ALTER ROLE nextcloud WITH PASSWORD '$nextcloud_password'"
'';
serviceConfig = {
User = pgsql.superUser;
Type = "oneshot";
RemainAfterExit = true;
};
};
2021-07-15 17:33:31 +02:00
}