6.02L Templating with variable lab - MartinWong06/grafana GitHub Wiki
Templating is a powerful feature in Grafana that allows you to create dynamic dashboards by using variables. Variables can be used to filter metrics, change the time range, and more. Here's an example of how to use templating with variables in Grafana:
-
Create a new dashboard in Grafana.
-
Click on the "Variables" button in the top left corner of the dashboard.
-
Click on the "New" button to create a new variable.
-
Choose a data source for your variable. For example, you could choose the Prometheus data source.
-
Choose a query for your variable. For example, you could choose a query that returns a list of hostnames.
-
Choose a display name for your variable. For example, you could name it "Host".
-
Choose a "Type" for your variable. For example, you could choose "Query".
-
Click "Add" to save your variable.
-
Now you can use your variable in your dashboard. For example, you could use it to filter metrics by hostname. To do this, add a new panel to your dashboard and choose a metric that includes the hostname in its label. Then, add a "Where" clause to your query that filters the data by your variable. For example, if your variable is named "$host", your query might look like this:
metric_name{hostname="$host"}
Example
label_values(up,job)
- You can also use your variable to change the time range of your dashboard. For example, you could create a dropdown that allows you to select a time range. To do this, create a new variable and choose a "Type" of "Interval". Then, add a new panel to your dashboard and choose a metric. Set the time range of the panel to use your variable. For example, if your variable is named "$time_range", your query might look like this:
This will allow you to select a time range using the dropdown, and the panel will automatically update to show the data for the selected time range.
metric_name{hostname="$host"}[$time_range]