Skip to main content

Dashboard Variables

Introduction

Dashboard variables are one of Grafana's most powerful features, allowing you to create dynamic, interactive dashboards that users can customize on the fly. Variables act as placeholders for values that can change, such as server names, application instances, time ranges, or any other parameter that might affect your visualizations.

By implementing variables in your Grafana dashboards, you can:

  • Create a single dashboard that serves multiple scenarios instead of duplicating dashboards
  • Allow users to filter and explore data based on their specific needs
  • Dynamically change queries and panel titles without editing dashboard JSON
  • Improve performance by letting users focus on specific data subsets

Understanding Variable Basics

Variables in Grafana work as dynamic placeholders that can be referenced in your queries. When you create a variable, it becomes available from a dropdown menu at the top of your dashboard.

Variable Types

Grafana offers several types of variables to suit different needs:

Variable TypeDescription
QueryVariable values are generated from a query (like a metric query)
CustomDefine the values manually using a comma-separated list
Text boxAllows users to enter any value
ConstantDefine a hidden value that can be used in queries
Data sourceSelect a data source
IntervalDefine time spans
Ad hoc filtersKey/value filters that are automatically added to all queries

Creating Your First Variable

Let's create a simple query variable that allows users to select from a list of servers.

Step 1: Access Variable Settings

  1. Navigate to your dashboard
  2. Click the gear icon in the top right to open dashboard settings
  3. Select "Variables" from the left menu
  4. Click "Add variable"

Step 2: Configure the Variable

For a basic server selection variable:

Name: server
Label: Server
Type: Query
Data source: Your Prometheus/InfluxDB/etc.
Query: label_values(node_cpu_seconds_total, instance)
Sort: Alphabetical (asc)

In this example, we're using a Prometheus data source to fetch all server instances that have reported CPU metrics.

Step 3: Using Variables in Queries

After creating a variable, you can reference it in queries using the syntax $variableName or ${variableName}.

For Prometheus (PromQL):

node_memory_MemAvailable_bytes{instance="$server"} / node_memory_MemTotal_bytes{instance="$server"} * 100

For InfluxDB:

SELECT mean("usage_idle") FROM "cpu" WHERE "host" = '$server' AND $timeFilter GROUP BY time($__interval)

Step 4: Apply to Dashboard Elements

You can also use variables in:

  • Panel titles: Memory Usage - $server
  • Text panels: Displaying metrics for server: $server
  • Annotations
  • Links

Advanced Variable Techniques

Multi-Value Selection

Enable users to select multiple values:

  1. In variable settings, enable "Multi-value" option
  2. In queries, use the regex parameter to handle multiple selections:
node_cpu_seconds_total{instance=~"$server"}

The =~ operator in PromQL allows for regex matching, which Grafana uses to inject multiple values.

Chained Variables (Dependent Variables)

Variables can depend on other variables, creating a filtering effect:

// First variable - Environment
Name: environment
Query: label_values(environment)

// Second variable - Dependent on Environment
Name: server
Query: label_values(node_cpu_seconds_total{environment="$environment"}, instance)

Using Variables in Variable Queries

You can reference a variable within another variable's query:

// Application variable depends on both environment and server
Name: application
Query: label_values(app_metrics{environment="$environment", instance="$server"}, app_name)

Practical Examples

Example 1: Server Performance Dashboard

Let's create a comprehensive server monitoring dashboard with variables:

  1. Create these variables:

    • datacenter (Query variable for selecting datacenter)
    • server (Query variable dependent on datacenter)
    • interval (Interval variable with options: 1m,5m,10m,30m,1h,6h,12h,1d)
  2. Use in query:

rate(node_cpu_seconds_total{instance="$server", mode!="idle"}[$interval])

This allows users to select a specific server in a specific datacenter and adjust the time interval for the rate function.

Example 2: Application Monitoring

For monitoring multiple applications:

  1. Set up these variables:

    • app (Query variable for application name)
    • instance (Query variable for application instance)
    • errorThreshold (Custom variable: 1,5,10,15,20)
  2. Create an alert panel that references these variables:

sum(rate(app_error_count{application="$app", instance="$instance"}[5m])) > $errorThreshold

Example 3: Business Metrics Dashboard

For business users monitoring product performance:

  1. Create variables:

    • product (Query variable for product lines)
    • region (Query variable for geographical regions)
    • compareWith (Custom variable: previous_day,previous_week,previous_month,previous_year)
  2. Use in query to show comparative metrics:

// Current period
sum(sales_total{product="$product", region="$region"})

// Comparison period (using template function)
sum(sales_total{product="$product", region="$region", time_period="${__timeFrom($compareWith)"})

Global Variables

Grafana provides built-in global variables you can use in any dashboard:

VariableDescription
$__intervalCalculated interval based on time range and panel width
$__fromStart of current time selection in ms epoch
$__toEnd of current time selection in ms epoch
$__dashboardCurrent dashboard name
$__orgCurrent organization ID
$__userCurrent user's login handle

Usage example:

// Dynamically adjust grouping based on time range
SELECT mean(value) FROM measurement WHERE $timeFilter GROUP BY time($__interval)

Variable Formatting

Grafana allows you to format variable values using different syntax:

  • ${var} - Default variable expansion
  • ${var:raw} - No escaping applied
  • ${var:regex} - Regex escaping
  • ${var:lucene} - Lucene escaping
  • ${var:glob} - Glob escaping
  • ${var:json} - JSON string escaping
  • ${var:csv} - Comma separated values
  • ${var:text} - Text representation
  • ${var:percentencode} - Percent encoding

Best Practices

  1. Descriptive naming: Use clear variable names and labels
  2. Default values: Set sensible defaults for variables
  3. Organize variables: Place the most commonly changed variables first in the dashboard
  4. Performance: For large datasets, use regex filtering at the data source level when possible
  5. Documentation: Add text panels explaining how to use the dashboard variables
  6. Testing: Verify all combinations of variables work as expected

Troubleshooting Common Issues

Variable Not Updating

If a dependent variable isn't updating when you change its parent:

  1. Check "Refresh" settings for the variable
  2. Ensure "On Dashboard Load" or "On Time Range Change" is selected
  3. Verify the variable query syntax is correct

Too Many Variable Options

For variables with many options:

  1. Enable "Include All option"
  2. Add filtering to the variable query
  3. Consider using text box variables instead

No Data Showing in Visualizations

If panels show "No data" after selecting variables:

  1. Check query syntax using variable references
  2. Confirm the data exists for the selected variable values
  3. Use Grafana's "Query Inspector" to see the exact queries being sent

Summary

Dashboard variables transform static Grafana dashboards into powerful, interactive tools for data exploration. By implementing variables correctly, you can:

  • Create flexible dashboards that serve multiple use cases
  • Allow users to customize their view without editing the dashboard
  • Reduce dashboard clutter and maintenance overhead
  • Enable sophisticated data filtering and comparison

With practice, you'll be able to design dashboards that are both user-friendly and technically powerful, making your monitoring solution more effective for everyone in your organization.

Additional Resources

  • Try creating a dashboard with at least three interdependent variables
  • Experiment with different variable types to understand their strengths
  • Create a dashboard template that uses variables for all query parameters
  • Explore Grafana's template functions for advanced variable manipulation

Exercises

  1. Create a dashboard that uses variables to monitor multiple services across different environments
  2. Implement a dashboard with time range variables that allow comparing current metrics with historical data
  3. Design a business metrics dashboard that allows drilling down from product categories to specific items using chained variables
  4. Create a variable that dynamically adjusts alert thresholds based on the selected service or application


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)