From 42d5df1e3d787ed23153a1aa4c5ed2dc1fc2d842 Mon Sep 17 00:00:00 2001
From: Fynn <fynn.becker@hs-hannover.de>
Date: Fri, 26 Aug 2022 14:55:06 +0200
Subject: [PATCH] Ensure monitor_postgrest works for all configs

postgrest-formula allows for configuration of multiple instances on the
same machine. Because multiple instances have distinct configurations,
the local check script can not assume the `admin-server-port` setting to
be present for all instances.
If no instance has the setting specified, the state ensures removal of
the local check script.
---
 checkmk/custom-files/local/monitor-postgrest |  2 ++
 checkmk/debian/monitor_postgrest.sls         | 11 +++++++++--
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/checkmk/custom-files/local/monitor-postgrest b/checkmk/custom-files/local/monitor-postgrest
index bf49ed4..e32c45a 100644
--- a/checkmk/custom-files/local/monitor-postgrest
+++ b/checkmk/custom-files/local/monitor-postgrest
@@ -3,8 +3,10 @@
 instance_names=()
 instance_admin_ports=()
 {% for instance_name, instance_conf in instances.items() %}
+{% if 'admin-server-port' in instance_conf['config'] %}
 instance_names+=("{{ instance_name }}")
 instance_admin_ports+=("{{ instance_conf['config']['admin-server-port'] }}")
+{% endif %}
 {% endfor %}
 
 function check_endpoint() {
diff --git a/checkmk/debian/monitor_postgrest.sls b/checkmk/debian/monitor_postgrest.sls
index 7c9cb2a..7816267 100644
--- a/checkmk/debian/monitor_postgrest.sls
+++ b/checkmk/debian/monitor_postgrest.sls
@@ -1,8 +1,11 @@
-{% set instances = salt['pillar.get']("postgrest:instances") %}
+{% set has_ports_configured = salt['pillar.get']("postgrest:instances").values()|selectattr("config", "defined")|selectattr("config.admin-server-port", "defined") %}
 
+{% set file_path= '/usr/lib/check_mk_agent/local/monitor-postgrest' %}
 hsh_checkmk_monitor_postgrest_plugin:
+{% if has_ports_configured|list %}
+{% set instances = salt['pillar.get']("postgrest:instances") %}
   file.managed:
-    - name: /usr/lib/check_mk_agent/local/monitor-postgrest
+    - name: {{ file_path }}
     - source: salt://checkmk/custom-files/local/monitor-postgrest
     - template: jinja
     - context:
@@ -10,3 +13,7 @@ hsh_checkmk_monitor_postgrest_plugin:
     - mode: 755
     - user: root
     - group: root
+{% else %}
+  file.absent:
+    - name: {{ file_path }}
+{% endif %}
-- 
GitLab