Prometheus 支持通过基本认证(又称 "basic auth")来连接 Prometheus 表达式浏览器和 HTTP API。
NOTE: 本教程介绍的是连接到 Prometheus 实例的基本认证。Prometheus 也支持在从 Prometheus 实例连接到抓取目标时使用基本认证。
对密码进行哈希处理
假设你希望所有访问 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
让我们创建一个 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 http://localhost:9090/graph
这将返回 401 Unauthorized 响应,因为你没有提供有效的用户名和密码。
要成功使用基本认证访问 Prometheus 端点,例如 /metrics 端点,请使用 -u 标志提供正确的用户名,并在提示时输入密码:
curl -u admin http://localhost: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 端点的用户进行身份验证。