使用基本认证保护 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 端点的用户。