relabel_config
重新標記是一個功能強大的工具,可以在目標的標籤集被抓取之前重寫它,每個採集配置可以配置多個重寫標籤設置,並按照配置的順序來應用於每個目標的標籤集。
目標重新標籤之後,以__開頭的標籤將從標籤集中刪除的。
如果使用只需要臨時的存儲臨時標籤值的,可以使用_tmp作爲前綴標識。
relabel的action類型
- replace: 對標籤和標籤值進行替換。
- keep: 滿足特定條件的實例進行採集,其他的不採集。
- drop: 滿足特定條件的實例不採集,其他的採集。
- hashmod: 這個我也沒看懂啥意思,囧。
- labelmap: 這個我也沒看懂啥意思,囧。
- labeldrop: 對抓取的實例特定標籤進行刪除。
- labelkeep: 對抓取的實例特定標籤進行保留,其他標籤刪除。
常用action的測試
在測試前,同步下配置文件如下。
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets:
rule_files:
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node_export'
static_configs:
- targets:
- deliver-database:9100
- basic-database:9100
- ETL:9100
- APP3:9100
- APP5:9100
- APP4:9100
- QCD1:9100
- QCD2:9100
- QCA1:9100
以上的機器,我已經在 hosts 做好解析了。
此時如果查看target信息,如下圖。
這些都是默認的 label ,因爲系統生成的 label 都是以__
開頭的,目標重新標籤之後,以__
開頭的標籤將從標籤集中刪除的。
replace
比如將所有 labels 中的 instance 的 9100 端口去掉
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets:
rule_files:
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node_export'
static_configs:
- targets:
- deliver-database:9100
- basic-database:9100
- ETL:9100
- APP3:9100
- APP5:9100
- APP4:9100
- QCD1:9100
- QCD2:9100
- QCA1:9100
relabel_configs:
- source_labels:
- "__address__"
regex: "(.*):9100"
target_label: "instance"
action: replace
replacement: "$1"
重啓服務查看 target 信息如下圖:
說下上面的配置:
- source_labels 指定我們我們需要處理的源標籤, 我們這裏處理
__address__
- target_labels 指定了我們要 replace 後的標籤名字, 我們這裏選擇
instance
- action 指定 relabel 動作,這裏使用 replace 替換動作。
- regex 去匹配源標籤
__address__
的值,"(.*):9100"
代表匹配這個表情9100前部分 - replacement 指定的替換後的標籤(target_label)對應的數值,採用正則引用方式獲取的。
keep
比如只採集所匹配名稱爲 APP* 的機器。
修改配置文件如下
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets:
rule_files:
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node_export'
static_configs:
- targets:
- deliver-database:9100
- basic-database:9100
- ETL:9100
- APP3:9100
- APP5:9100
- APP4:9100
- QCD1:9100
- QCD2:9100
- QCA1:9100
relabel_configs:
- source_labels:
- "__address__"
regex: "APP.*"
action: keep
重啓之後查看 target 如下圖,可以看到只採集 APP 開頭的服務器。
drop
在上面的基礎上,修改 action 爲 drop。
重啓之後,target 如下圖
action 爲 drop,其實和 keep 是相似的, 不過是相反的, 只要 source_labels 的值匹配APP.*
的實例不會被採集。 其他的實例會被採集。
給 target 手動增加 label
配置文件修改爲如下
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets:
rule_files:
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node_export'
static_configs:
- targets:
- deliver-database:9100
- basic-database:9100
- ETL:9100
- APP3:9100
- APP5:9100
- APP4:9100
- QCD1:9100
- QCD2:9100
- QCA1:9100
labels:
os: "linux"
relabel_configs:
- source_labels:
- "__address__"
regex: "(.*):9100"
target_label: "instance"
action: replace
replacement: "$1"