blob: 836bf71d004d62f50a94f897d1e39c22e82605dd [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
Samuel Shuertc6f63032024-12-31 11:09:23 -05005{ lib, config, pkgs, ... }:
Skyler Grey7d539492024-06-08 23:18:57 +00006let
7 cfg = config.clicks.services.postgres;
8in
9{
10 options.clicks.services.postgres = {
11 enable = lib.mkEnableOption "Postgresql DB";
Samuel Shuertc6f63032024-12-31 11:09:23 -050012 latest = lib.mkEnableOption "Use pinned PG version, otherwise default to 15.10";
Skyler Grey7d539492024-06-08 23:18:57 +000013
14 databases = lib.mkOption {
15 type = lib.types.attrsOf lib.types.str;
16 description = "An attrset of databases to password files, these databases and users will be automatically created";
17 default = { };
18 example = {
19 headscale = "/run/secrets/headscale_db_password";
20 };
21 };
22
23 secretRequiredGroups = lib.mkOption {
24 type = lib.types.listOf lib.types.str;
25 description = "A list of groups that the postgres superuser should be given to read the password file secrets";
26 default = [ ];
27 example = [ "headscale" ];
28 };
29 };
30
31 config =
32 let
33 databasesAsList = lib.attrsets.attrsToList cfg.databases;
34 in
35 lib.mkIf cfg.enable {
36 services.postgresql = {
37 enable = true;
Samuel Shuertc6f63032024-12-31 11:09:23 -050038 package = if cfg.latest then pkgs.postgresql else pkgs.postgresql_15;
Skyler Grey7d539492024-06-08 23:18:57 +000039
40 settings = {
41 listen_addresses = lib.mkForce lib.clicks.constants.hosts.standard;
42 log_connections = true;
43 logging_collector = true;
44 log_disconnections = true;
45 log_destination = lib.mkForce "syslog";
46 };
47
48 ensureDatabases = lib.lists.forEach databasesAsList (database: database.name);
49 ensureUsers = lib.lists.forEach databasesAsList (database: {
50 name = database.name;
51 ensureDBOwnership = true;
52 });
53
54 # method database user address auth-method
55 authentication = "host all all samenet scram-sha-256";
56 };
57
58 systemd.services.postgresql.restartTriggers = [ config.systemd.services.postgresql.postStart ];
59
60 systemd.services.postgresql.postStart = (
61 lib.pipe databasesAsList [
62 (map (database: ''
63 $PSQL -tAc "ALTER USER ${database.name} PASSWORD '$(cat ${database.value})';"
64 ''))
65 (lib.concatStringsSep "\n")
66 ]
67 );
68
69 users.users.${config.services.postgresql.superUser}.extraGroups = cfg.secretRequiredGroups;
70
71 clicks.storage.impermanence.persist.directories = [ "/var/lib/postgresql" ];
72 };
73}