Setting or Replacing Label Values

A common use case for relabeling is to set or overwrite the value of a label. This can be done using the replace action, which is the default if the action field is not specified.

Rule Structure

A replace relabeling rule has the following structure:

action: replace
source_labels: [<source label name list>]
separator: <source labels separator>      # Defaults to ';'
regex: <regular expression>               # Defaults to '(.*)' (matching any value)
replacement: <replacement string>         # Defaults to '$1' (using the first capturing group as a replacement)
target_label: <target label>

This action performs the following steps, in sequence:

  1. It concatenates the values of the labels listed in source_labels using the provided separator value.
  2. It tests whether the regular expression in regex matches the concatenated string from the previous step. If there is no match, it skips to the next relabeling rule and does not replace anything.
  3. If there is a match, it extracts the values of any regular expression capturing groups (see the RE2 regular expression documentation) and substitutes any reference ($1, $2, ...) to these groups in the replacement string with their values.
  4. It stores the regex-substituted replacement string as the new value for the label provided as target_label.

Use Case Examples

Let's look at some example use cases for the replace action.

Setting a Fixed Label Value

The simplest replace example is just setting a label to a fixed value. For example, you could set the env label to the value production like this:

action: replace
replacement: production
target_label: env

Note that we don't even have to set most of the rule's fields, since the defaults already work well for this case (matching the entire source label and using that as the replacement string).

Replacing the Scrape Port

A more involved example is overriding the port that an instance is scraped on. You can replace the __address__ label's port with the fixed port 80 like this:

action: replace
source_labels: [__address__]
regex: ([^:]+)(?::\d+)?   # The first group matches the host, the second matches the port.
replacement: '$1:80'
target_label: __address__