Journal

Writing down the things I learned. To share them with others and my future self.

13 May 2020

Set Default Value of Prometheus Label if not set

I had to implement the following behaviour in a prometheus relabel config:

Given two labels A and B. I want to set A to the value of label B, if and only if A is empty/not-set.

First I tried to find a proper action in the prometheus relabel_config, but I did not find any. Luckily the replace action only replaces the target label if the given regex matches. Therefore, the following relabel config has the wanted property:

1
2
3
4
5
6
- source_labels: [A, B]
  action: replace
  separator: ";"
  regex: ;(.*)
  replacement: $1
  target_label: A

It works because the values of the source_labels are joined by the separator. After concatenating the two values, the regex is matched against the concatenated values. The regex above, only matches if A is empty. The value of B will be matched by the first and only group reference. Hence replace only replaces the value of label A if it is empty.