Sometimes you may want to take a whole set of source labels and map their values into a new set of differently prefixed new label names. The
labelmap action allows this. The most common use case for
labelmap is taking a group of hidden/temporary metadata labels from service discovery and mapping them into permanent target labels.
labelmap relabeling rule has the following structure:
action: labelmap regex: <regular expression> # Defaults to '(.*)' (matching any value) replacement: <replacement string> # Defaults to '$1' (using the first capturing group as a replacement)
In contrast to the previous relabeling actions we learned about, the
labelmap action regex-matches and acts on label names, not label values.
labelmap action performs the following steps, in sequence:
- It matches the regular expression in
regexagainst all label names.
- It then copies any matching values of matching label names to new label names that are determined by the
replacementstring, after substituting any reference (
$2, ...) to capturing groups in
Use Case Examples
Let's look at an example use case for the
Mapping Kubernetes Service Labels
When using Kubernetes-based service discovery to discover pod endpoints, you may want the final target labels for each endpoint to also contain the Kubernetes service labels. The Kubernetes service discovery provides these in a set of labels with the naming pattern
__meta_kubernetes_service_label_<labelname>. We can extract the
<labelname> part of those metadata labels and map the corresponding label values over to a new set of label names that start with a
k8s_ prefix, like this:
action: labelmap regex: __meta_kubernetes_service_label_(.+) replacement: 'k8s_$1'