Prometheus allows renaming labels in the following places:
- During metric scrape. In this case you need to add the following relabeling rules into
metric_relabel_configs section at the corresponding scrape_config:
metric_relabel_configs:
- source_labels: [__name__, name]
regex: "node_systemd_unit_state;(.+)"
target_label: unit_name
- source_labels: [__name__, name]
regex: "node_systemd_unit_state;(.+)"
target_label: name
replacement: ""
The first rule copies name label value into unit_name label for metrics with node_systemd_unit_state name. The second rule sets name label value to an empty string (e.g. deletes the name label) for metrics with node_systemd_unit_state name.
label_join(
label_join(node_systemd_unit_state, "unit_name", "", "name"),
"name", "", "non_existing_label"
)
The inner label_join() copies name label into unit_name label. The outer label_join() substitutes the original name label with an empty string (e.g. remove the name label).
As you can see, label_join() isn't the best function for label renaming. The label_replace() isn't the best function for label renaming too. While Prometheus doesn't provide better solutions for label renaming, such solution exist in Prometheus-like systems such as VictoriaMetrics (I'm the author of this system). It provides label_move() function:
label_move(node_systemd_unit_state, "name", "unit_name")
Additionally, VictoriaMetrics provides if option for conditional relabeling rules. For example, the following relabeling rules are equivalent to the rules above, but are easier to understand and maintain:
metric_relabel_configs:
- if: 'node_systemd_unit_state{name!=""}'
source_labels: [name]
target_label: unit_name
- if: 'node_systemd_unit_state{name!=""}'
target_label: name
replacement: ""