How can I write conditionals in a PromQL regex?

Viewed 1685

I have a custom Grafana variable $var, which I use in my Prometheus queries to retrieve some data. Based on the value of this variable, the label value of the metric I'm using should be changed accordingly. In other words, I would like to use a conditional on this variable within regex. See example below:

some_metric{my_label=~"(?($var=val1)label_val1|label_val2)"}

The above query would result in my_label being equal to label_val1 if $var equals to val1, and label_val2 in all other cases. However, this doesn't seem to be supported by the RE2 syntax, which Prometheus uses for regular expressions. Is there any other way to achieve this behavior?

Note: the $var variable controls most of the other variables in my dashboard, and it already has a key/value mapping in place, so I cannot go for this workaround. I was thinking about creating an additional custom variable, which would also depend on $var, however it seems that Grafana does not support this either.

1 Answers

One workaround could be the key/value custom variable available since Grafana Version 7.3.

You would create a variable and have key value pairs:

val1 : label_val1, val2 : label_val2

enter image description here


Then in your PromQL, you would reference the variable as normal:

some_metric{my_label=~"$var"}

Related