某個 https 證書突然過期,導致某個業務出現問題。理論上來說這個問題不應該存在,證書到期時間是固定的,更新也不費時間,但這個問題還是存在。
使用 Grafana 7 中new table visualization功能,使用Prometheus監視證書的到期日期,並使用Grafana進行
展示。
這就是它的樣子,所有證書一目了然:證書到期之前的剩余時間,HTTP狀態碼和連接時間等等

導出和獲取指標
使用 blackbox_exporter 收集此數據需要的一切指標,blackbox exporter 可以監控 http/https 頁面,ip、端口等。
在這里我們使用它監控 [host:port] ,可以獲取SSL證書信息,並從中自動捕獲到期日期,並使用probe_ssl_earliest_cert_expiry指標計算剩余時間。
以下是配置,非常簡單:
modules:
http_2xx:
prober: http
http:
preferred_ip_protocol: "ip4"
tls_config:
insecure_skip_verify: true
- prometheus.yml 添加一個 job
- job_name: 'blackbox'
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- https://xx.com
- https://baidu.com
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: <blackboxexporter_IP>:9115 # Blackbox exporter scraping address
展示所有指標
現在已經收集到了指標,接下來就要在 Grafana 展示這些內容了。使用https://grafana.com/grafana/dashboards/13230 這個模板。
下面是幾個盡量簡單的例子:

剩余時間:
probe_ssl_earliest_cert_expiry-time()
HTTP 狀態碼:
probe_http_status_code
所有 HTTP duration 查詢:
probe_http_duration_seconds{phase="resolve"}
probe_http_duration_seconds{phase="connect"}
probe_http_duration_seconds{phase="tls"}
probe_http_duration_seconds{phase="processing"}
probe_http_duration_seconds{phase="transfer"}
轉換功能
我們還利用了Grafana 7的 Transform 功能:在 instance 字段上使用 Outer join 將所有查詢的結果一起顯示在一行上。

該組織字段轉換也被用來過濾顯示在我們的面板上

告警
雖然我們在 Grafana 做了展示,但是我們不會經常去看的,所以還是要在 Prometheus 設置告警,這樣在證書過期時會收到通知。
- name: ssl_expiry
rules:
- alert: Ssl Cert Will Expire in 30 days
expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 30
for: 5m
labels:
severity: warning
annotations:
summary: "SSL certificate will expire soon on (instance {{ $labels.instance }})"
description: "SSL certificate expires in 30 days\n VALUE = {{ $value }}\n LABELS: {{ $labels }}"
當然你也可以修改為其他時間,比如 10 天,那表達式就改為:
expr: probe_ssl_earliest_cert_expiry - time() < 86400 * 10
別忘了同步修改警報名稱和描述
