Help build the future of open source observability software Open positions

Check out the open source projects we support Downloads

Grot cannot remember your choice unless you click the consent notice at the bottom.

Ask Us Anything: How to Alias Dashboard Variables in Grafana in SQL

Ask Us Anything: How to Alias Dashboard Variables in Grafana in SQL

2019-07-17 2 min

Recently a question came up from a customer, and I was surprised we didn’t have an easy answer for it:

How can you translate some esoteric ID or serial number, such as fe03-s3-x883, into a user-friendly name such as “harry” or “alice”?

In a regular templating language, it would be easy to do via a map file or similar, but to do this with Grafana is a little more complicated. If you’re using SQL (which Grafana now supports), there’s an easy trick to get this done.

The customer was asking in the context of repeating over a row, but the following answer applies for any variables.

Let’s assume some contrived, but simple, data to explain the concept.

service_iddisplay_name
x0032s24Alice
x123s997Bob
y83l93Charlie

We need to store this data in a datasource that Grafana can access. I used a MariaDB/MySQL database, but Postgres will also work.

Data in MySQL
Data in MySQL

In my lab environment, I just did a quick install of the MariaDB packages on my Grafana server and used the test database with no authentication. In production you would of course set things up with more security in mind. Pay particular attention to the warning message at the bottom there.

Next, we’ll put the data into the database. If you’ve got more than a handful of entries, look into the many ways of getting data into MySQL tables.

Getting data into MySQL tables
Getting data into MySQL tables

So, now we have the data in there we want.

Data in MariaDB table
Data in MariaDB table

In your dashboard, go into the Dashboard Settings menu and the Variables section and click new for a new variable and fill it in similarly to what’s below.

Creating a new variable
Creating a new variable

The critical bits are in the query. Whatever database column is assigned as __text is used whenever the variable is displayed and whatever is assigned to __value is used as the actual value when Grafana makes a query. The documentation of the mysql data source has a bit more information on what you can do with this.

Let’s try it on a simple dashboard.

Simple dashboard
Simple dashboard

Here you can see that although the dropdown is showing the display names we want, the query variable, $service_id, is actually using the value stored in the database to do the query.

Dashboard showing values stored in database
Dashboard showing values stored in database

It works for the graph title also.

And you can even loop over it.

Dashboard showing looping
Dashboard showing looping

Got a question for us about monitoring best practices? Email us at help@grafana.com.