Search code examples
prometheus

Prometheus relabel_configs - multiple target labels


I'm using Prometheus with file_sd_configs sources. Using this approach labels can be extracted from the filename. E.g.:

file_sd_configs:
  - files:
    - /etc/prometheus/targets/hostname_http_prod.yml
    - /etc/prometheus/targets/hostname_http_dev.yml
relabel_configs:
  - source_labels: [__meta_filepath]
    regex: "/etc/prometheus/targets/hostname_http_(dev|tst|uat|prod)\\.yml"
    target_label: env

I'd like to take this a step further and populate multiple target labels using a single Regex. E.g.

file_sd_configs:
  - files:
    - /etc/prometheus/targets/hostname_http_prod.yml
    - /etc/prometheus/targets/hostname_http_dev.yml
    - /etc/prometheus/targets/hostname_db_prod.yml
relabel_configs:
  - source_labels: [__meta_filepath]
    regex: "/etc/prometheus/targets/hostname_([^_]+)_(dev|tst|uat|prod)\\.yml"
    target_label: type
    replacement: $2
    target_label: env

Is this a supported method or does the source and regex need to be specified multiple times?


Solution

  • The following relabeling rules should create type and env labels based on the __meta_filepath label value:

    - source_labels: [__meta_filepath]
      regex: "etc/prometheus/targets/hostname_([^_]+)_(dev|tst|uat|prod)\\.yml"
      replacement: "$1"
      target_label: type
    - source_labels: [__meta_filepath]
      regex: "etc/prometheus/targets/hostname_([^_]+)_(dev|tst|uat|prod)\\.yml"
      replacement: "$2"
      target_label: env
    

    Basically it contains two relabeling rules with the same regex part, but with distinct replacement and target_label parts. This relabeling rule can be debugged here.