Sub topic 13
Using variables to switch between servers
This chapter assumes you have a Grafana dashboard with panels that query Prometheus, such as the CPU, memory, and disk queries from the PromQL chapters. It also assumes the Prometheus data source is connected. Here you replace hard-coded server names with dashboard variables, so one dashboard can show any server, several servers, or all of them.
Why variables
Without variables, you copy a dashboard for each server and edit every query. Each copy drifts from the others. A dashboard variable is a named value that Grafana substitutes into queries before it sends them to Prometheus. The dashboard shows the variable as a drop-down at the top of the page.
The idea is that Prometheus already knows which servers exist. Every series carries an instance label, so Grafana can ask Prometheus for the list of values and build the drop-down from it. When you add a server to prometheus.yml, it appears in the drop-down without any dashboard edit.
How the substitution works
The diagram shows the path from the drop-down to the data.
Grafana does the substitution as text replacement. Prometheus never sees $instance. It receives an ordinary query with the chosen values already in place.
Creating a query variable
Open the dashboard, go to Settings, then Variables, and add a new variable with these values:
- Type: Query
- Name:
instance. This is the name you use as$instancein queries. - Label:
Server. This is the text shown next to the drop-down. - Data source: your Prometheus data source
- Query:
label_values(up{job="node"}, instance)
label_values(metric, label) is a Grafana helper, not PromQL. It returns every distinct value of label found on series of metric. The query uses up filtered to the node job because up exists for every target. It lists a server even if one of its collectors is broken. Filtering on the job keeps Prometheus's own localhost:9090 target out of the list.
The same variable in the dashboard's JSON model looks like this:
{
"templating": {
"list": [
{
"name": "instance",
"label": "Server",
"type": "query",
"datasource": { "type": "prometheus", "uid": "prometheus" },
"query": {
"query": "label_values(up{job=\"node\"}, instance)",
"refId": "PrometheusVariableQueryEditor-VariableQuery"
},
"refresh": 2,
"multi": true,
"includeAll": true,
"sort": 1
}
]
}
}The uid must match the UID of your data source. Check it under Connections, then Data sources. If you provision the data source from a file, add a uid: line to it so the value stays stable across installs.
Using the variable in queries
Edit each panel and replace the hard-coded server with the variable. Use the regex matcher =~, not =, because a multi-value variable expands to a pattern such as (server1.example.com:9100|server2.example.com:9100).
# CPU utilisation for the selected servers, in percent
100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle", instance=~"$instance"}[$__rate_interval])))
# Memory in use for the selected servers, in percent
100 * (1 - node_memory_MemAvailable_bytes{instance=~"$instance"} / node_memory_MemTotal_bytes{instance=~"$instance"})
# Fraction of disk space still available on the selected servers
node_filesystem_avail_bytes{instance=~"$instance", fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{instance=~"$instance", fstype!~"tmpfs|overlay"}$__rate_interval is a built-in Grafana variable. It picks a range that suits the panel's resolution and the data source's scrape interval, so you stop guessing a value like [5m]. The two other options are:
- Include All option: adds an "All" entry that selects every value. Grafana expands it to a regex that matches every server.
- Multi-value: lets the user tick several servers at once. Each one gets its own line in a time series panel.
In the panel's legend field, set {{instance}} so each line is labelled with its server name.
Variable types
Query variables are the most useful, but Grafana offers others.
| Type | What it holds | Typical use |
|---|---|---|
| Query | Values returned by a data source query | Server, job, or mountpoint lists |
| Custom | A fixed comma-separated list you type in | Choices such as `warning,critical` |
| Interval | Time spans such as `1m,5m,1h` | Letting users change the rate window |
| Data source | A data source of a chosen type | Switching between two Prometheus servers |
| Constant | A hidden fixed value | A shared label value or prefix |
| Text box | Free text typed by the user | Filtering by a hostname fragment |
Chaining variables
One variable's query can use another variable. A first variable job uses label_values(up, job). The instance variable then uses:
label_values(up{job="$job"}, instance)Selecting a job narrows the server list. Grafana orders the drop-downs by dependency and refreshes the child when the parent changes. A third variable can follow the same pattern. A mountpoint variable can use label_values(node_filesystem_size_bytes{instance="$instance"}, mountpoint) to list only the filesystems of the chosen server.
Refresh and sorting
The Refresh setting decides when Grafana re-runs the variable query:
- On dashboard load runs it once per page load. This is enough for server lists.
- On time range change runs it again whenever the time picker changes. It makes the list show only servers that reported data in the selected window. It costs one extra query per change.
Set Sort to alphabetical so the list stays in a predictable order.
Common problems
Other causes of empty panels or empty drop-downs:
- The drop-down is empty. The variable query returns nothing. Run
up{job="node"}in Grafana's Explore view. If that returns no series, the problem is in scraping, not in Grafana. - The variable shows
$instanceliterally. The variable name in the query does not match the name in settings. Names are case-sensitive. - A server that was removed still appears. With a long time range and refresh on time change, Grafana lists series seen at any point in the range.
- Dots in names cause strange matches. Grafana escapes regex special characters in multi-value expansion. If you write your own regex around
$instance, remember that.matches any character. - A custom All value. If you set a custom All value such as
.*, it also matches series with noinstancelabel. Leave it empty unless you need it.
Exercise
A panel uses node_load1{instance="$instance"}. A user selects two servers in a multi-value drop-down and the panel goes empty. What is wrong, and what is the fix?
Show answer
Grafana expands the selection to a regex like (server1.example.com:9100|server2.example.com:9100), but the = matcher compares it as a literal string, so no series match. Change the matcher to =~: node_load1{instance=~"$instance"}.
Exercise
Write the query for a mountpoint variable that lists only the filesystems of the server chosen in $instance, and say how the dashboard behaves when the user changes the server.
Show answer
Use label_values(node_filesystem_size_bytes{instance="$instance"}, mountpoint). Because it depends on $instance, Grafana refreshes the mountpoint list whenever the server selection changes. This works as written when $instance is single-value. For a multi-value instance, use instance=~"$instance".