Grafana: Variables

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Grafana 13.3.x.

To do this by hand, follow Variables, Filters and Repeats.

A dashboard without variables is a picture of one service. A dashboard with variables is a tool: the same panels answer the question for any service, route, environment or cluster, and the viewer chooses which with a drop-down instead of asking someone to clone and edit the dashboard. For monitoring this matters twice. During an incident the person holding the pager should reach the failing instance in two clicks, and a team that maintains one parameterised dashboard per kind of workload (instead of one dashboard per workload) keeps every copy consistent. How the dashboards are laid out is covered by Building Dashboards and Dashboard Design Principles; this page covers the variable machinery itself. The running example is the "Bookshelf service health" dashboard from the hands-on lab.

What a variable is

A variable is a named placeholder that Grafana replaces before the query leaves the browser. It can appear in queries, panel titles and descriptions, links, repeat options and transformations. Viewers change it from a control above the dashboard, and the new value is written to the URL as var-<name>=value, so a link to a dashboard carries its context with it. Grafana distinguishes three kinds of variable:

  • Dashboard variables are created inside one dashboard and are the subject of most of this page.

  • Cross-dashboard variables are defined once for the organisation or a folder and reused by several dashboards (public preview in 13.3, see below).

  • Built-in variables such as the time range, the dashboard name and the signed-in user are always available.

flowchart LR job["Variable: job (query)"] --> svc["Variable: application (query, uses job)"] svc --> route["Variable: route (query, uses application)"] route --> panels["Panels: query uses job, application and route"] interval["Variable: window (interval)"] --> panels filters["Filters and Group by (dashboard wide)"] --> panels url["URL: var-application=bookshelf"] -. sets .-> svc

The eight variable types

Grafana 13 offers eight types. The table is the decision aid; the details follow.

Type Use it for Bookshelf example

Query

Values that already exist in a data source and change over time.

Every uri label seen on the HTTP server metric.

Custom

A short, fixed list that no data source can supply.

env: prod, staging.

Text box

Free-form input, useful for high-cardinality values or one value shared by many panels.

A request id or ISBN to narrow a Loki log panel.

Constant

A hidden value used to avoid repeating a long string.

A path prefix or a shared label matcher.

Data source

Switching the whole dashboard between instances of one data source type.

Prometheus lab versus a second Prometheus.

Interval

Letting the viewer choose the grouping step, with an optional Auto entry.

A window of 1m, 5m, 1h.

Filters (Filter and Group by)

Dashboard-wide key/value filters and, for Prometheus and Loki, group-by keys, without defining a variable per label.

Narrow every panel to status="500".

Switch

A boolean-like toggle between two configured values.

Show or hide the debug filter in a query.

Query variables

A query variable asks a data source for its options. For Prometheus the editor offers query types instead of free text: Label names, Label values (a label, optionally restricted to a metric), Metrics (names matching a regex), Query result (the result of a PromQL query) and Series query. A Classic query type with the old label_values(metric, label) syntax still exists but is marked deprecated, so a new dashboard should use the dedicated types. A Query variable also has a Regex option that filters or rewrites the returned options (only the named capture groups text and value are supported), a Sort option (disabled by default), a Static options tab, and a Refresh setting that decides when the options are queried: on dashboard load or on time range change.

For the Bookshelf the route variable is a Label values variable on the label uri of the metric http_server_requests_seconds_count, restricted to application="bookshelf". The label filter makes the list shorter and, through it, the variable can depend on another variable (see chained variables). Because label_values does not accept range variables, a variable that must follow the dashboard time range uses the Query result type, for example query_result(max_over_time(up{job="$job"}[${__range_s}s]) == 1) with Refresh set to On time range change.

Source: Prometheus template variables and Add a query variable. The Prometheus label and query functions are described in the Prometheus cheat sheet.

Custom, text box and constant variables

A Custom variable holds a comma-separated list; key1 : value1,key2 : value2 gives each entry a display text and a different value, and a JSON array of objects gives multi-property variables, where one choice maps to several source-specific values:

[
  { "value": "1", "text": "Production", "cluster": "bookshelf-prod", "namespace": "shop" },
  { "value": "2", "text": "Staging", "cluster": "bookshelf-stg", "namespace": "shop-stg" }
]

A panel then references a property with ${env.cluster}. A Text box variable is empty by default (or starts with the configured value) and suits values with too many possibilities for a drop-down. A Constant variable is hidden and never changes; exporting a dashboard turns it into an import option, which makes it a convenient place for an environment-specific value that the importer should supply.

Data source, interval and switch variables

A Data source variable has a Type (for example Prometheus) and an optional Name filter regex. Panels select the data source with the variable, which lets one dashboard serve a production and a staging Prometheus. An Interval variable lists steps (default 1m,10m,30m,1h,6h,12h,1d,7d,14d,30d) and can add an Auto entry that divides the time range by a Step count (default 30), bounded below by a Min interval. A Switch variable offers a value pair (true and false, 1 and 0, yes and no, or custom), which is useful for turning on a filter inside a query. The value is substituted as text before the query runs, and neither PromQL nor LogQL can compare it or branch on it, so give the two custom values query fragments instead: with 5.. and .+ the PromQL http_server_requests_seconds_count{status=~"$only_errors"} keeps 5xx or every status, and with ERROR and .* the LogQL {application="bookshelf"} |~ "$only_errors" keeps error lines or all of them. The comparison and ternary forms in Grafana’s own example are not valid in either language.

Filters, and Filter and Group by

The Filters variable is dashboard-wide: the viewer adds key operator value filters and every panel that uses the chosen data source applies them, so the author does not have to define one variable per label. Grafana 13.1 renamed the older "Ad hoc filters" to Filter and Group by and added group-by keys for Prometheus and Loki; InfluxDB, Elasticsearch, OpenSearch and the Dashboard data source support filters only. In the dashboard schema the variable is still "kind": "AdhocVariable".

In the editor you choose the data source, optional default filters, whether Enable group by is on (Prometheus and Loki only), default group-by keys, optional static key dimensions and whether custom values are allowed. Viewers can also filter from a panel: hover over a data point and click the add-filter icon, or Filter out this value to exclude it. Cross-filtering needs a field override with the Filter from values property (filterable in provisioned JSON), and Histogram, State timeline, Status history and Time series panels additionally need group by to be enabled. A panel whose data lacks the filtered key returns no data, which is the usual explanation for a panel that "goes empty" after a filter is added.

Variable syntax and formats

Three forms are supported. $name is the shortest but cannot be followed directly by word characters, ${name} works anywhere (use it in ${env}-cluster), and ${name:format} chooses how a multi-value variable is rendered. The legacy &#91;&#91;name&#93;&#93; form is deprecated and scheduled for removal. An invalid format falls back to glob. The formats most useful for monitoring are listed below, with servers = ['test1', 'test2'].

Format Result Typical use

regex

(test1|test2) (values escaped)

PromQL label matchers with =~

pipe

values joined by a vertical bar

Hand-built regexes, Loki line filters

csv

test1,test2

Query parameters, SQL IN lists

lucene

("test1" OR "test2")

Elasticsearch and Kibana-style queries

singlequote, doublequote, sqlstring

'test1','test2', "test1","test2", 'test1','test2' (with the single quote doubled inside values)

Quoting for SQL and JSON

json

["test1", "test2"]

Passing the selection to an API

queryparam

var-servers=test1&var-servers=test2

Links to other dashboards

text

display text of the selection

Panel titles

raw

no data-source-specific escaping

When automatic escaping breaks a query

Prometheus and InfluxDB regex queries escape multi-value variables automatically, so the default rendering is already a regex such as (host1|host2|host3); Graphite uses a glob ({host1,host2}) and Elasticsearch a Lucene expression. The practical rule for Prometheus is to compare with =~ and never with = as soon as Multi-value or Include All is on:

sum by (uri) (
  rate(http_server_requests_seconds_count{application="bookshelf", uri=~"$uri", status=~"$status"}[$__rate_interval])
)

Multi-value, Include All and what can go wrong

Query and Custom variables have three selection options, all off by default: Multi-value, Include All option and Allow custom values (CSV custom variables only). Include All adds an All entry; the Custom all value is not escaped, so a regex such as .+ can be entered. Setting Include All with the custom all value .+ is also the way to start a dashboard with nothing preselected, because the first value is otherwise selected by default.

The failure modes are worth knowing before an incident exposes them:

  • All expands to a long regex. With a thousand routes the query text becomes enormous and slow. Use a custom all value (.+) so that All means "no filter".

  • A hidden variable with Include All defaults to the first value. To make All the default, temporarily show the variable, select All, save, hide it again and save.

  • Automatic escaping breaks a hand-written pattern. Turn off Multi-value and Include All, or use the raw format.

  • The drop-down shows stale options. A Query variable refreshed only on dashboard load does not follow the time range; choose On time range change when the options depend on it.

  • The variable name differs from its label. Links and URLs use the name, never the label.

Chained variables

A query can reference another variable, in which case Grafana detects the dependency and refreshes the dependent variable when its parent changes. The Bookshelf dashboard chains job to application and application to route (the lab’s metrics carry no environment label):

Variable job          Query     label_values(http_server_requests_seconds_count, job)
Variable application  Query     label_values(http_server_requests_seconds_count{job="$job"}, application)
Variable route        Query     label_values(http_server_requests_seconds_count{job="$job", application="$application"}, uri)
                                Multi-value, Include All with custom all value .+, refresh On time range change

There is no technical limit on the depth, but each level adds queries before the panels can refresh, so a change of the root variable runs a query for every dependent variable first. Place variables without dependencies at the top of the list and each variable after the one it depends on (the drop-downs appear in list order and the UI does not show dependencies). Static variables such as Custom in the chain reduce the query count. The easiest way to build a link in the chain is to duplicate the parent variable and extend its query.

Built-in variables

Built-in variables are available in every dashboard and query. The ones that matter for monitoring are:

Variable Meaning

$__interval, $__interval_ms

Grouping interval computed from the time range and panel width; used for SQL, Elasticsearch, InfluxDB and Graphite aggregation steps.

$__rate_interval

Interval for rate() and increase() on Prometheus, computed as max($__interval + scrape_interval, 4 * scrape_interval). Prefer it to a fixed window or to $__interval.

$__range, $__range_s, $__range_ms

Length of the dashboard time range (Prometheus and Loki).

$__from, $__to

Start and end of the range in epoch milliseconds.

$__timeFilter

The time range as a SQL-style expression.

$__dashboard, ${__org.name}, ${__user.login}

Dashboard name, organisation name, signed-in user.

$__url_time_range

from=...&to=... parameters for building links.

$__rate_interval has pitfalls: the data source’s Scrape interval must match the Prometheus configuration, a Min step on the query overrides it, and when the query reads a recording rule the window should be fixed (for example [5m]).

Every variable is mirrored in the URL: ?var-service=catalogue sets a single value and repeating the parameter (&var-route=/books&var-route=/authors) sets several. A Filters variable uses var-filter=key%7C%3Dvalue (the pipe and the equals sign URL-encoded). Time uses from and to (epoch milliseconds, or relative values such as now-5m), time and time.window give a centred range, and timezone sets the time zone. A variable with skipUrlSync set to true in the dashboard JSON stays out of the URL (Constant variables do so by default). These parameters are what makes a variable usable as a deep link from an alert notification, from a runbook or from another dashboard; the link options are covered in Annotations and Links.

Repeating panels, rows and tabs

A multi-value variable can also generate layout. In a panel’s Repeat options choose Repeat by variable; Grafana makes one copy per selected value, horizontally (with a Max per row) or vertically in a custom layout. Only the source panel is editable, edits apply to all copies, and layout changes to copies reset on reload. Putting the variable name in the panel, row or tab title tells the viewer which copy is which. A repeated panel per route is useful for a handful of values and harmful for hundreds, since every copy runs its own queries.

Cross-dashboard variables (public preview in 13.3)

Cross-dashboard variables are defined once under Dashboards > Variables with a scope: Dashboards (the root, available to every dashboard of the organisation) or a folder (available to dashboards in that folder). They support the same types as dashboard variables except Filters. A dashboard adds them from Add new element > Variable by choosing the type Global or folder variable, and can pick individual variables or All global / All folder. The feature is in public preview with limited support, needs the feature toggle grafana.dashboardGlobalVariables in the configuration (or a request to Support), may change before general availability, and the page documents no permission model. Until it is stable, keep a dashboard variable as the fallback for anything alert-critical.

Managing and inspecting variables

In edit mode the sidebar lists variables: select one to edit it, use the clone icon (the copy is named with copy and a number), the trash icon to delete, and drag to reorder or to move a control between Above dashboard, Controls menu and Hidden. The Show dependencies button at the bottom of the list opens a diagram of which variables depend on which, the quickest way to find a cycle or an orphan before a viewer does. Each variable’s Display option (above the dashboard, label hidden, in the controls menu or hidden) decides how prominent it is.

Variables as code

A variable is part of the dashboard model, so it can be provisioned, exported and reviewed like any other dashboard content. In the V2 resource model the variables are a variables array of kinds (QueryVariable, CustomVariable, SwitchVariable, AdhocVariable and so on), described in Library Panels, JSON Model and Versions. Keep the saved current value out of reviews where possible, since it changes whenever someone saves the dashboard with a different selection.

Verify in the lab

  1. Open "Bookshelf service health" and select a different application or route; the dependent drop-downs must refresh and the address bar must show the matching var- parameters.

  2. Open a panel’s inspector (Inspect > Query) and read the interpolated expression: it must contain the chosen values, as a regex group when more than one is selected.

  3. Select All with a custom all value of .+ and confirm that the panel still returns data and the query stays short.

  4. Copy the URL with var- parameters into a private window; the same selection should load.

  5. Change the dashboard time range and check whether a Query result variable refreshes.

In the books

McCollam (Getting Started with Grafana, chapter 10) walks through Custom, Query and Data source variables, chaining, repeating panels and variables in URLs, and Salituro (Learn Grafana 10.x, chapter 10) covers template variables and ad hoc filters on an Elasticsearch data source and repeating rows and panels. Both predate the Switch variable, the rename of ad hoc filters to Filter and Group by with group-by keys, tabs as repeatable containers, and cross-dashboard variables. The &#91;&#91;name&#93;&#93; syntax used in older examples is deprecated, and the Classic query type for Prometheus variables has been replaced by dedicated query types. The reasoning (variables remove duplication, chain them from broad to narrow) is unchanged.