blob: 0f6b71f4389fa14121b47bd7fa4517f782832d3d [file] [log] [blame]
# SPDX-FileCopyrightText: 2024 Clicks Codes
#
# SPDX-License-Identifier: GPL-3.0-only
{ lib, config, ... }:
let
cfg = config.clicks.services.postgres;
in
{
options.clicks.services.postgres = {
enable = lib.mkEnableOption "Postgresql DB";
databases = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
description = "An attrset of databases to password files, these databases and users will be automatically created";
default = { };
example = {
headscale = "/run/secrets/headscale_db_password";
};
};
secretRequiredGroups = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "A list of groups that the postgres superuser should be given to read the password file secrets";
default = [ ];
example = [ "headscale" ];
};
};
config =
let
databasesAsList = lib.attrsets.attrsToList cfg.databases;
in
lib.mkIf cfg.enable {
services.postgresql = {
enable = true;
settings = {
listen_addresses = lib.mkForce lib.clicks.constants.hosts.standard;
log_connections = true;
logging_collector = true;
log_disconnections = true;
log_destination = lib.mkForce "syslog";
};
ensureDatabases = lib.lists.forEach databasesAsList (database: database.name);
ensureUsers = lib.lists.forEach databasesAsList (database: {
name = database.name;
ensureDBOwnership = true;
});
# method database user address auth-method
authentication = "host all all samenet scram-sha-256";
};
systemd.services.postgresql.restartTriggers = [ config.systemd.services.postgresql.postStart ];
systemd.services.postgresql.postStart = (
lib.pipe databasesAsList [
(map (database: ''
$PSQL -tAc "ALTER USER ${database.name} PASSWORD '$(cat ${database.value})';"
''))
(lib.concatStringsSep "\n")
]
);
users.users.${config.services.postgresql.superUser}.extraGroups = cfg.secretRequiredGroups;
clicks.storage.impermanence.persist.directories = [ "/var/lib/postgresql" ];
};
}