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 Type | Description |
---|---|
Query | Variable values are generated from a query (like a metric query) |
Custom | Define the values manually using a comma-separated list |
Text box | Allows users to enter any value |
Constant | Define a hidden value that can be used in queries |
Data source | Select a data source |
Interval | Define time spans |
Ad hoc filters | Key/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
- Navigate to your dashboard
- Click the gear icon in the top right to open dashboard settings
- Select "Variables" from the left menu
- 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:
- In variable settings, enable "Multi-value" option
- 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:
-
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)
-
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:
-
Set up these variables:
app
(Query variable for application name)instance
(Query variable for application instance)errorThreshold
(Custom variable: 1,5,10,15,20)
-
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:
-
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)
-
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:
Variable | Description |
---|---|
$__interval | Calculated interval based on time range and panel width |
$__from | Start of current time selection in ms epoch |
$__to | End of current time selection in ms epoch |
$__dashboard | Current dashboard name |
$__org | Current organization ID |
$__user | Current 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
- Descriptive naming: Use clear variable names and labels
- Default values: Set sensible defaults for variables
- Organize variables: Place the most commonly changed variables first in the dashboard
- Performance: For large datasets, use regex filtering at the data source level when possible
- Documentation: Add text panels explaining how to use the dashboard variables
- 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:
- Check "Refresh" settings for the variable
- Ensure "On Dashboard Load" or "On Time Range Change" is selected
- Verify the variable query syntax is correct
Too Many Variable Options
For variables with many options:
- Enable "Include All option"
- Add filtering to the variable query
- Consider using text box variables instead
No Data Showing in Visualizations
If panels show "No data" after selecting variables:
- Check query syntax using variable references
- Confirm the data exists for the selected variable values
- 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
- Create a dashboard that uses variables to monitor multiple services across different environments
- Implement a dashboard with time range variables that allow comparing current metrics with historical data
- Design a business metrics dashboard that allows drilling down from product categories to specific items using chained variables
- 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! :)