Problems with Regex Relabel and Optional Characters

253 views
Skip to first unread message

Russ Robinson

unread,
Jun 14, 2022, 12:38:55 PM6/14/22
to Prometheus Users
Wonder if I can get some help.  We are seeing an oddity here.  Within my configuration, we are using kubernetes_sd_configs and I have the following in the relabel section of my scrape config:

- source_labels: [__meta_kubernetes_namespace]
  separator: ;
  regex: (^mykub-test--[^-]*)
  target_label: kubernetes_customer_env_name
  replacement: $1
  action: replace

This works fine if the namespace is just mykub-test--herenow  but not for namespaces like mykub-test--anothertest2--test123 .  Basically, I want to strip off the "--test123" (or ignore it) in the later example.  Any suggestions?

Brian Candler

unread,
Jun 15, 2022, 1:53:57 AM6/15/22
to Prometheus Users
It's not clear what your requirements are.  Is it possible that values after the double-dash might themselves contain a single dash, like
mykub-test--another-test--test-123
and if so, what should happen?

Could there be additional double-dash separated sections like
mykub-test--anothertest--test123--test456
and if so, what should happen?

If you want mykub-test--a-a--b-b--c-c to become mykub-test--a-a, then you could try this (untested):

- source_labels: [__meta_kubernetes_namespace]
  regex: (mykub-test--.*?)(--.*)?
  target_label: kubernetes_customer_env_name
  replacement: $1
  action: replace

.*? applies the "non-greedy" modifier to make the first .* match the smallest possible number of times, whereas (xxx)? means match the subexpression zero or one times.  For more info see

If you need to do more complex multi-step processing then you can use temporary labels.  Names starting __tmp_ are reserved for this purpose (i.e. are guaranteed not to clash with other prometheus-internal labels).

The following will split the label into two, on the first instance of "--" which appears in the string, requiring at least one instance to occur:

- source_labels: [__meta_kubernetes_namespace]
  regex: (.*?)--(.*)
  target_label: __tmp_nsprefix
  replacement: $1
  action: replace

- source_labels: [__meta_kubernetes_namespace]
  regex: (.*?)--(.*)
  target_label: __tmp_nssuffix
  replacement: $2
  action: replace

Reply all
Reply to author
Forward
0 new messages