在Prometheus查询中使用Grafana变量遇解析错误
Ah, I see the issue here—let's break this down and fix it! The root problem is that PromQL itself doesn't natively support raw variable references at the start of a query. The $ character isn't part of standard PromQL syntax, so the Prometheus parser throws an error when it encounters that leading $. Variable substitution isn't handled by PromQL itself—it's managed by the tool you're using to run the query (like Grafana, Alertmanager, or a custom client) before the query gets sent to Prometheus.
Here's how to resolve this:
Leverage your tool's built-in variable system
Most tools that interact with Prometheus (like Grafana) let you define variables that get replaced with actual values before the query is executed. For example:- In your tool, create a variable (say, named
target_metric) and set its value tototalaccuracy_total. - In your PromQL query, reference the variable using the syntax your tool supports. For Grafana, this would be either
$target_metricor${target_metric}. So your query would look like:
Or if you want to run an aggregation:$target_metric
Your tool will replacesum($target_metric) by (instance)$target_metricwithtotalaccuracy_totalbefore sending the query to Prometheus, so Prometheus receives a fully valid PromQL statement.
- In your tool, create a variable (say, named
Keep in mind: Prometheus Web UI doesn't support custom variables
If you're testing directly in the Prometheus Web UI's query editor, you can't use custom$variables here. You'll need to write the full metric name directly, liketotalaccuracy_total.Double-check variable naming rules
Make sure your variable name doesn't include characters that your tool considers invalid. While underscores are generally fine, some tools might restrict variable names to lowercase letters, numbers, and underscores—avoid spaces or special characters in variable names to prevent unexpected issues.
内容的提问来源于stack exchange,提问作者HandsDown

