如何通过Relabeling为Blackbox Exporter探针添加HTTP请求头
解决方案:通过Blackbox Exporter动态从标签获取请求头监控IP目标
针对用IP地址监控但需要指定Host头(或其他自定义请求头)的场景,完全可以通过Blackbox的模板特性+Prometheus的标签传递来实现,无需频繁修改核心配置。具体配置步骤如下:
1. 修改Blackbox模块配置,启用动态请求头
在blackbox.yml的http模块中,添加headers配置项,使用Go模板语法引用目标标签的值。以Host头为例:
modules: https_2xx: prober: http timeout: 5s http: valid_status_codes: [200, 403, 401, 404] method: GET no_follow_redirects: false fail_if_ssl: false fail_if_not_ssl: false tls_config: insecure_skip_verify: true preferred_ip_protocol: "ip4" # 从目标的dns_name标签读取Host头值 headers: Host: "{{.Labels.dns_name}}" http_2xx: prober: http timeout: 5s http: valid_status_codes: [200, 403, 401, 404] method: GET no_follow_redirects: false fail_if_ssl: false fail_if_not_ssl: false preferred_ip_protocol: "ip4" # 从目标的dns_name标签读取Host头值 headers: Host: "{{.Labels.dns_name}}"
如果需要添加其他自定义请求头,直接在headers下新增即可,比如X-Custom-Header: "{{.Labels.x_custom_header}}"。
2. 调整Prometheus任务配置,传递自定义标签
需要在Prometheus的relabel_configs中添加labelmap规则,把目标的自定义标签(比如dns_name)保留并传递给Blackbox,否则Blackbox无法读取到这些标签值:
- job_name: blackbox_http file_sd_configs: - files: - /etc/prometheus/blackbox.json metrics_path: /probe relabel_configs: - source_labels: [__address__] target_label: __param_target - source_labels: [__param_target] target_label: instance - source_labels: [module] target_label: __param_module # 保留指定的自定义标签,这里匹配dns_name标签 - action: labelmap regex: ^dns_name$ # 若有其他自定义请求头标签,可添加类似规则,比如: # - action: labelmap # regex: ^x_custom_header$ - target_label: __address__ replacement: localhost:9115
3. 更新文件服务发现的目标配置
在blackbox.json中,给需要指定Host头的IP目标添加dns_name标签(或对应自定义请求头的标签)即可:
[ { "labels": { "module": "https_2xx", "__shard": "sd", "job": "https_2xx", "project": "project_name", "service": "service_name", "VirtualServer": "some_identifier", "dns_name": "example.com" }, "targets": [ "https://10.10.0.1" ] }, { "labels": { "module": "http_2xx", "__shard": "nc", "job": "http_2xx", "project": "project_name", "service": "service_name", "VirtualServer": "another_identifier", "dns_name": "test.example.com" }, "targets": [ "http://10.10.0.2" ] } ]
原理说明
Blackbox Exporter支持使用Go模板语法访问Prometheus传递过来的目标标签,通过{{.Labels.标签名}}就能直接引用标签值作为请求头内容。而Prometheus的labelmap规则负责把自定义标签保留下来,传递给Blackbox的探针请求,这样就能实现完全基于标签的动态请求头配置,新增目标时只需要在blackbox.json中添加对应标签即可,无需修改核心配置文件。
内容的提问来源于stack exchange,提问作者Vadym B
相关产品推荐
相关产品推荐

