Prometheus 支持对 Prometheus 表达式浏览器和 HTTP API 的连接进行基本身份验证(又称“基本认证”)。
假设您想要求所有访问 Prometheus 实例的用户都提供用户名和密码。在本例中,使用 admin
作为用户名,并选择您想要的任何密码。
首先,生成密码的 bcrypt 哈希值。要生成哈希密码,我们将使用 python3-bcrypt。
假设您正在运行类似 Debian 的发行版,运行 apt install python3-bcrypt
来安装它。还有其他替代方法可以生成哈希密码;对于测试,您也可以使用网络上的 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 文件(文档),内容如下
basic_auth_users:
admin: $2b$12$hNf2lSsxfm0.i4a.1kVpSOVyBCfIB51VRjgBUyv6kdnyTlgWj81Ay
您可以使用 promtool check web-config web.yml
验证该文件
$ promtool check web-config web.yml
web.yml SUCCESS
您可以向文件中添加多个用户。
您可以使用以下方式启动带有 Web 配置文件的 Prometheus
$ prometheus --web.config.file=web.yml
您可以使用 cURL 与您的设置进行交互。试试这个请求
curl --head https://127.0.0.1:9090/graph
这将返回一个 401 Unauthorized
响应,因为您未能提供有效的用户名和密码。
要使用基本认证成功访问 Prometheus 端点,例如 /metrics
端点,请使用 -u
标志提供正确的用户名,并在提示时提供密码
curl -u admin https://127.0.0.1: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 端点的用户的身份。
本文档是 开源的。请通过提交问题或拉取请求来帮助改进它。