Mapping Labelsets

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.

Rule Structure

A 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.

The labelmap action performs the following steps, in sequence:

  1. It matches the regular expression in regex against all label names.
  2. It then copies any matching values of matching label names to new label names that are determined by the replacement string, after substituting any reference ($1, $2, ...) to capturing groups in replacement.

Use Case Examples

Let's look at an example use case for the labelmap action.

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'