{ lib, config, pkgs, ... }: let cfg = config.services.vm_postgresql; in { options.services.vm_postgresql = { enable = lib.mkEnableOption "Enable minimal config"; }; config = lib.mkIf cfg.enable { age.secrets = { nextcloudDBPass = { file = ./secrets/nextcloudDBPass.age; owner = "postgres"; }; giteaDBPass = { file = ./secrets/giteaDBPass.age; owner = "postgres"; }; authentikDBPass = { file = ./secrets/authentikDBPass.age; owner = "postgres"; }; grafanaDBPass = { file = ./secrets/grafanaDBPass.age; owner = "postgres"; }; }; services.postgresql = { enable = true; package = pkgs.postgresql_16; enableTCPIP = true; settings.port = 5432; authentication = " host nextcloud nextcloud 192.168.1.45/32 md5 host gitea gitea 192.168.1.14/32 md5 host authentik authentik 192.168.1.125/32 md5 host grafana grafana 192.168.1.27/32 md5 host onlyoffice onlyoffice 192.168.1.46/32 md5 "; initialScript = pkgs.writeText "init-sql-script" '' CREATE ROLE nextcloud WITH LOGIN CREATEDB; CREATE DATABASE nextcloud; GRANT ALL PRIVILEGES ON DATABASE nextcloud TO nextcloud; CREATE ROLE gitea WITH LOGIN CREATEDB; CREATE DATABASE gitea; GRANT ALL PRIVILEGES ON DATABASE gitea TO gitea; CREATE ROLE authentik WITH LOGIN CREATEDB; CREATE DATABASE authentik; GRANT ALL PRIVILEGES ON DATABASE authentik TO authentik; CREATE ROLE grafana WITH LOGIN CREATEDB; CREATE DATABASE grafana; GRANT ALL PRIVILEGES ON DATABASE grafana TO grafana; CREATE ROLE onlyoffice WITH LOGIN CREATEDB; CREATE DATABASE onlyoffice; GRANT ALL PRIVILEGES ON DATABASE onlyoffice TO onlyoffice; ''; }; # Stolen from https://discourse.nixos.org/t/assign-password-to-postgres-user-declaratively/9726/3 # This is an awful situation systemd.services.postgresql.postStart = let nextcloudDBPass = config.age.secrets.nextcloudDBPass.path; giteaDBPass = config.age.secrets.giteaDBPass.path; authentikDBPass = config.age.secrets.authentikDBPass.path; grafanaDBPass = config.age.secrets.grafanaDBPass.path; in '' $PSQL -tA <<'EOF' DO $$ DECLARE password TEXT; BEGIN password := trim(both from replace(pg_read_file('${nextcloudDBPass}'), E'\n', ''')); EXECUTE format('ALTER ROLE nextcloud WITH PASSWORD '''%s''';', password); password := trim(both from replace(pg_read_file('${giteaDBPass}'), E'\n', ''')); EXECUTE format('ALTER ROLE gitea WITH PASSWORD '''%s''';', password); password := trim(both from replace(pg_read_file('${authentikDBPass}'), E'\n', ''')); EXECUTE format('ALTER ROLE authentik WITH PASSWORD '''%s''';', password); password := trim(both from replace(pg_read_file('${grafanaDBPass}'), E'\n', ''')); EXECUTE format('ALTER ROLE grafana WITH PASSWORD '''%s''';', password); password := trim(both from replace(pg_read_file('${onlyofficeDBPass}'), E'\n', ''')); EXECUTE format('ALTER ROLE onlyoffice WITH PASSWORD '''%s''';', password); END $$; EOF ''; networking.firewall.allowedTCPPorts = [5432]; }; }