背景介绍
Node Exporter v1.0.0之前的版本不支持TLS和认证,所以默认情况下是通过http暴露的/metrics,默认没有任何访问限制。对于有些环境硬性要求不允许使用http提供访问,和对安全性要求较高必须有认证的情况下,原来只能通过额外增加一层反向代理(如nginx)来解决。但给每个node_export配1个nginx,这显然这太复杂太重了。
从 v1.0.0版本开始实验性的支持https和基本认证。 从 Node Exporter 开始到后续其他的组件,都将支持 TLS 和 basic auth, 同时也列出了最新的安全基准(默认情况下都支持 TLS v1.2 及以上)。下面让我们来看看具体配置。
生成证书
openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 -keyout node_exporter.key -out node_exporter.crt -subj "/C=CN/ST=Beijing/L=Beijing/O=test.cn/CN=localhost"
命令执行完生成两个文件
node_exporter.crt node_exporter.key
配置Node Exporter 开启 TLS
解压,并将node_exporter
和node_exporter.crt node_exporter.key
放在同一个目录
编写配置文件,并保存为 config.yaml(文件名自定义)
tls_server_config:
cert_file: node_exporter.crt
key_file: node_exporter.key
使用配置文件启动启动node_exporter
./node_exporter --web.config=config.yaml
当你看到如下日志,说明TLS已生效
level=info ts=2020-09-11T01:42:42.079Z caller=node_exporter.go:191 msg="Listening on" address=:9100
level=info ts=2020-09-11T01:42:42.079Z caller=tls_config.go:200 msg="TLS is enabled and it cannot be disabled on the fly." http2=true
验证:
# curl localhost:9100/metrics
Client sent an HTTP request to an HTTPS server.
# curl https://localhost:9100/metrics
curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
#### 使用-k跳过证书验证就可以获得metrics了
curl -k https://localhost:9100/metrics
Prometheus 配置
增加如下配置后,在Prometheus UI中应该就能看到target了
- job_name: 'node_exporter'
scheme: https
tls_config:
ca_file: node_exporter.crt
static_configs:
- targets: ['localhost:9100']
添加 Basic Auth
生成密码,如果没有htpasswd命令请自行安装
这里我只用它来生成了密码 hash , 没有传递用户名。
# htpasswd -nBC 12 '' | tr -d ':\n'
修改node_exporter的配置文件config.yaml
tls_server_config:
cert_file: node_exporter.crt
key_file: node_exporter.key
basic_auth_users:
# 当前设置的用户名为 prometheus , 可以设置多个
prometheus: $2y$12$WLw2sYa.NY0NhTn0EvpefLHeuG.l7TAH9Wzd9HlK1H8ZuDo9EAGKK0i
使用配置文件启动启动node_exporter
./node_exporter --web.config=config.yaml
验证,将提示401
# curl -Ik https://localhost:9100/metrics
HTTP/1.1 401 Unauthorized
Content-Type: text/plain; charset=utf-8
Www-Authenticate: Basic
X-Content-Type-Options: nosniff
Date: Fri, 11 Sep 2020 02:22:13 GMT
Content-Length: 13
修改Prometheus 配置
- job_name: 'node_exporter'
scheme: https
tls_config:
ca_file: node_exporter.crt
basic_auth:
username: prometheus
password: prometheuspassword
static_configs:
- targets: ['localhost:9100']
修改后重新加载配置文件,再到Prometheus UI中查看target状态是否正常
# curl -X POST http://localhost:9090/-/reload
或者
# killall -HUP prometheus