使用基本認證保護 Prometheus API 和 UI 端點

Prometheus 支援 基本認證 (亦稱“基本認證”),用於連線到 Prometheus 表示式瀏覽器HTTP API

注意本教程涵蓋了 Prometheus 例項的基本認證連線。Prometheus 例項 抓取目標 進行連線也支援基本認證。

對密碼進行雜湊處理

假設您希望所有訪問 Prometheus 例項的使用者都提供使用者名稱和密碼。在本例中,使用 admin 作為使用者名稱,並選擇您喜歡的任何密碼。

首先,生成密碼的 bcrypt  雜湊。為了生成雜湊密碼,我們將使用 python3-bcrypt。

讓我們透過執行 apt install python3-bcrypt 來安裝它,假設您正在執行一個類似 Debian 的發行版。還有其他生成雜湊密碼的方法;為了測試,您也可以使用 線上 bcrypt 生成器 

這是一個使用 python3-bcrypt 提示輸入密碼並進行雜湊處理的 Python 指令碼

import getpass
import bcrypt

password = getpass.getpass("password: ")
hashed_password = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
print(hashed_password.decode())

將該指令碼儲存為 gen-pass.py 並執行它

$ python3 gen-pass.py

這應該會提示您輸入密碼

password:
$2b$12$hNf2lSsxfm0.i4a.1kVpSOVyBCfIB51VRjgBUyv6kdnyTlgWj81Ay

在此示例中,我使用了“test”作為密碼。

將該密碼儲存在某個地方,我們將在後續步驟中使用它!

建立 web.yml

讓我們建立一個 web.yml 檔案(文件),內容如下

basic_auth_users:
    admin: $2b$12$hNf2lSsxfm0.i4a.1kVpSOVyBCfIB51VRjgBUyv6kdnyTlgWj81Ay

您可以使用 promtool check web-config web.yml 驗證該檔案

$ promtool check web-config web.yml
web.yml SUCCESS

您可以向該檔案中新增多個使用者。

啟動 Prometheus

您可以按如下方式使用 Web 配置檔案啟動 Prometheus

$ prometheus --web.config.file=web.yml

測試

您可以使用 cURL 與您的設定進行互動。嘗試以下請求

curl --head https://:9090/graph

這將返回 401 Unauthorized 響應,因為您未能提供有效的使用者名稱和密碼。

要使用基本認證成功訪問 Prometheus 端點(例如 /metrics 端點),請使用 -u 標誌提供正確的使用者名稱,並在提示時提供密碼

curl -u admin https://:9090/metrics
Enter host password for user 'admin':

這應該會返回 Prometheus 指標輸出,看起來會是這樣

# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0.0001343
go_gc_duration_seconds{quantile="0.25"} 0.0002032
go_gc_duration_seconds{quantile="0.5"} 0.0004485
...

總結

在本指南中,您將使用者名稱和雜湊密碼儲存在 web.yml 檔案中,並使用該檔案中所需的引數啟動 Prometheus,以認證訪問 Prometheus HTTP 端點的使用者。

本頁內容