Can I use a Template Variable in the Metric Script Field

I’m trying to create a graph of normalized Throughput data. I have Throughput data points and I want to plot a graph of (Throughput / TotalThroughput) * 100, for any given period. I can use the Metric Script Field to apply a calculation to ‘_value’ (e.g. (_value / 6000000) * 100, given my TotalThroughput for the period is 6000000rpm), but the TotalThroughout will obviously change, based on the graph window.

Ideally, I need to be able to pick up, say, a Single Stat value for TotalThroughput dynamically and apply it to the Script Field as a variable, but I can’t see a way to do that! Another thought I had was to create a Template Variable that holds the TotalThroughput value, but I can’t see how to use a Template variable in the Script Field and have it interpreted before submitting the query. I know certain internal variables like ‘$interval’ and ‘$__interval_ms’ can be used in the field and they get interpreted before the query is submitted!

So, can I achieve what I need with Grafana? Can I reference dynamic variables or other metric values in the Metric Script Field?

My data source is Elasticsearch v5.4.0 and I’m using Grafana v4.6.0.


If internal variables are working it should work with defining a custom one as well.


How do I define and use a ‘custom’ variable. I tried creating a Template Variable like so…


…but if I use the value in a Script Calculation like so…


…it doesn’t work. The Query Inspector shows that the literal variable text (i.e. $TotalThroughput) is inserted in the query, rather than the value I assigned to the variable (i.e. 18174).


I just tried the following dashboard

And added (_value / $source) to the script field. This will of course create a bad query, but I can still see in query inspector that the template variable been replaced in the script field.

Could it be related to that you’re using a constant variable? What version of Grafana are you using?


I’m running Grafana v4.6.0 right now.

OK, I followed your lead and experimented using the link you provided. I created a Constant Variable and was able to get it to work! So I went back to my installation and reproduced exactly what I did while experimenting. It also worked! So then I recreated exactly what I did in my previous post, using the same variable name and value, and IT also now works!!

I don’t know why it’s working today and didn’t work all the previous days I tried. You can see in the screen shots I provided that it didn’t work before.

Anyway, thanks for the help. You kept me looking at the issue and I know I have options now. I hope it continues to work. :slight_smile:

1 Like