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.
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:
- It concatenates the values of the labels listed in
source_labelsusing the provided
- It tests whether the regular expression in
regexmatches the concatenated string from the previous step. If there is no match, it skips to the next relabeling rule and does not replace anything.
- 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 (
$2, ...) to these groups in the
replacementstring with their values.
- It stores the regex-substituted
replacementstring as the new value for the label provided as
Use Case Examples
Let's look at some example use cases for the
Setting a Fixed Label Value
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__