From ee58f7a4eef3a85ff7dda20c709e230a27cadff1 Mon Sep 17 00:00:00 2001 From: Noah Masur <7386960+nmasur@users.noreply.github.com> Date: Wed, 5 Jul 2023 14:19:54 -0600 Subject: [PATCH] abstract grafana in prometheus config --- modules/nixos/services/prometheus.nix | 29 ++++++++++++++------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/modules/nixos/services/prometheus.nix b/modules/nixos/services/prometheus.nix index 7977ee2..fb7e5df 100644 --- a/modules/nixos/services/prometheus.nix +++ b/modules/nixos/services/prometheus.nix @@ -6,10 +6,13 @@ default = null; }; - # If hosting Grafana, host local Prometheus and listen for inbound jobs. - # If not hosting Grafana, send remote Prometheus writes to primary host + config = let - config = lib.mkIf config.services.prometheus.enable { + # If hosting Grafana, host local Prometheus and listen for inbound jobs. If + # not hosting Grafana, send remote Prometheus writes to primary host. + isServer = config.services.grafana.enable; + + in lib.mkIf config.services.prometheus.enable { services.prometheus = { exporters.node.enable = true; @@ -17,10 +20,9 @@ job_name = "local"; static_configs = [{ targets = [ "127.0.0.1:9100" ]; }]; }]; - webExternalUrl = lib.mkIf config.services.grafana.enable - "https://${config.prometheusServer}"; + webExternalUrl = lib.mkIf isServer "https://${config.prometheusServer}"; # Web config file: https://prometheus.io/docs/prometheus/latest/configuration/https/ - webConfigFile = lib.mkIf config.services.grafana.enable + webConfigFile = lib.mkIf isServer ((pkgs.formats.yaml { }).generate "webconfig.yml" { basic_auth_users = { # Generate password: htpasswd -nBC 10 "" | tr -d ':\n' @@ -29,7 +31,7 @@ "$2y$10$r7FWHLHTGPAY312PdhkPEuvb05aGn9Nk1IO7qtUUUjmaDl35l6sLa"; }; }); - remoteWrite = lib.mkIf (!config.services.grafana.enable) [{ + remoteWrite = lib.mkIf (!isServer) [{ name = config.networking.hostName; url = "https://${config.prometheusServer}"; basic_auth = { @@ -41,20 +43,19 @@ }; # Create credentials file for remote Prometheus push - secrets.prometheus = lib.mkIf (!config.services.grafana.enable) { + secrets.prometheus = lib.mkIf (!isServer) { source = ../../../private/prometheus.age; dest = "${config.secretsDirectory}/prometheus"; owner = "prometheus"; group = "prometheus"; permissions = "0440"; }; - systemd.services.prometheus-secret = - lib.mkIf (!config.services.grafana.enable) { - requiredBy = [ "prometheus.service" ]; - before = [ "prometheus.service" ]; - }; + systemd.services.prometheus-secret = lib.mkIf (!isServer) { + requiredBy = [ "prometheus.service" ]; + before = [ "prometheus.service" ]; + }; - caddy.routes = lib.mkIf config.services.grafana.enable [{ + caddy.routes = lib.mkIf isServer [{ match = [{ host = [ config.prometheusServer ]; }]; handle = [{ handler = "reverse_proxy";