blob: 0f6b71f4389fa14121b47bd7fa4517f782832d3d [file] [log] [blame]
Skyler Grey7d539492024-06-08 23:18:57 +00001# SPDX-FileCopyrightText: 2024 Clicks Codes
2#
3# SPDX-License-Identifier: GPL-3.0-only
4
5{ lib, config, ... }:
6let
7 cfg = config.clicks.services.postgres;
8in
9{
10 options.clicks.services.postgres = {
11 enable = lib.mkEnableOption "Postgresql DB";
12
13 databases = lib.mkOption {
14 type = lib.types.attrsOf lib.types.str;
15 description = "An attrset of databases to password files, these databases and users will be automatically created";
16 default = { };
17 example = {
18 headscale = "/run/secrets/headscale_db_password";
19 };
20 };
21
22 secretRequiredGroups = lib.mkOption {
23 type = lib.types.listOf lib.types.str;
24 description = "A list of groups that the postgres superuser should be given to read the password file secrets";
25 default = [ ];
26 example = [ "headscale" ];
27 };
28 };
29
30 config =
31 let
32 databasesAsList = lib.attrsets.attrsToList cfg.databases;
33 in
34 lib.mkIf cfg.enable {
35 services.postgresql = {
36 enable = true;
37
38 settings = {
39 listen_addresses = lib.mkForce lib.clicks.constants.hosts.standard;
40 log_connections = true;
41 logging_collector = true;
42 log_disconnections = true;
43 log_destination = lib.mkForce "syslog";
44 };
45
46 ensureDatabases = lib.lists.forEach databasesAsList (database: database.name);
47 ensureUsers = lib.lists.forEach databasesAsList (database: {
48 name = database.name;
49 ensureDBOwnership = true;
50 });
51
52 # method database user address auth-method
53 authentication = "host all all samenet scram-sha-256";
54 };
55
56 systemd.services.postgresql.restartTriggers = [ config.systemd.services.postgresql.postStart ];
57
58 systemd.services.postgresql.postStart = (
59 lib.pipe databasesAsList [
60 (map (database: ''
61 $PSQL -tAc "ALTER USER ${database.name} PASSWORD '$(cat ${database.value})';"
62 ''))
63 (lib.concatStringsSep "\n")
64 ]
65 );
66
67 users.users.${config.services.postgresql.superUser}.extraGroups = cfg.secretRequiredGroups;
68
69 clicks.storage.impermanence.persist.directories = [ "/var/lib/postgresql" ];
70 };
71}