如何在Prometheus告警描述中将剩余过期秒数转为天数?
Prometheus alert templates don't support direct arithmetic operations (like division) on the $value variable within the template syntax—this is why your previous attempts to divide $value by 86400 failed. Instead, you need to compute remaining days either in your alert's PromQL expression or via a recording rule.
Option 1: Adjust the Alert Expression to Return Days Directly
Modify your alert rule's expression to calculate remaining days instead of seconds. This way, $value will already be in days when used in the annotation.
Example alert rule:
groups: - name: ssl_cert_alerts rules: - alert: SSLCertExpiringIn29Days expr: (probe_ssl_last_chain_expiry_timestamp_seconds - time()) / 86400 < 29 for: 5m annotations: description: "SSL certificate expires in {{ printf \"%.2f\" $value }} days" summary: "SSL certificate expiring soon for {{ $labels.instance }}"
- The expression
(probe_ssl_last_chain_expiry_timestamp_seconds - time()) / 86400converts remaining seconds to days by dividing by 86400 (seconds per day). printf "%.2f" $valueformats the days to two decimal places for readability.
Option 2: Use a Recording Rule to Precompute Remaining Days
If you need the remaining days metric for other queries or alerts, create a recording rule to precompute it once, then reference the new metric in your alert.
Step 1: Define the Recording Rule
Add this to your Prometheus rules configuration:
groups: - name: ssl_recording_rules rules: - record: probe_ssl_cert_remaining_days expr: (probe_ssl_last_chain_expiry_timestamp_seconds - time()) / 86400
Step 2: Create the Alert Using the Precomputed Metric
groups: - name: ssl_cert_alerts rules: - alert: SSLCertExpiringIn29Days expr: probe_ssl_cert_remaining_days < 29 for: 5m annotations: description: "SSL certificate expires in {{ printf \"%.2f\" $value }} days" summary: "SSL certificate expiring soon for {{ $labels.instance }}"
Key Notes
- Prometheus template functions are limited to formatting and label manipulation—all arithmetic must be handled in PromQL (either in the alert expression or recording rule).
- If you prefer a human-readable duration (e.g., "28d 4h 30m"), you can use the
humanizeDurationfunction with the original seconds value:
This requires keeping the alert expression in seconds, asdescription: "SSL certificate expires in {{ humanizeDuration $value }}"humanizeDurationexpects a value in seconds.
内容的提问来源于stack exchange,提问作者Lino Kaiser

