John Arrowwood
John Arrowwood

Reputation: 2460

Can you share code between multiple grafana scripted dashboards?

I have created a couple of scripted dashboards for Grafana. I'm about to create another. There are all kinds of utility functions that I created and copied from script to script. I would much rather employ good programming practice and import the code rather than copy-paste.

Can that be done? If so, how would one do it?

Upvotes: 2

Views: 595

Answers (1)

Erik Ostermueller
Erik Ostermueller

Reputation: 508

Yes, this can be done. This link suggests that SystemJS.import() can be used, although I have not tried it.

This github repo provides a detailed example using a different technique. Although its not mentioned in the slim Grafana scripted dashboard doc, some version of lodash.com (commit to include lodash) and jquery seem to be available to all scripted dashboards.

The owner of this repo, anryko, has figured out how to use these two libraries to reference your own utility scripts like you're talking about.

All scripted dashboards have a main script; getdash.sh is anryko's main script, as seen by the dash URL on the README.md:

http://grafanaIP/dashboard/script/getdash.js

If you look at the end of getdash.sh, you'll see this line that references code in other user(you)-provided scripts:

var dash = getDashApp(datasources, getDashConf());

For example:

Here is the part where getdash.js uses jquery and lodash to load the source files:

// loadScripts :: [scriptSourceStr] -> Promise([jQuery.getScript Result])
var loadScripts = function loadScripts (scriptSrcs) {
  var gettingScripts = _.map(scriptSrcs, function (src) {
    return $.getScript(src);
  });

  return Promise.all(gettingScripts);
};

Here is the lodash doc for the above _.map.

The function scriptedDashboard() (also in getdash.js) calls the above loadScripts(), passing it the paths to the source files like this:

loadScripts([
      'public/app/getdash/getdash.app.js',
      'public/app/getdash/getdash.conf.js'
    ]).then(function () {

To be honest, I haven't yet looked further under the covers to see how all this makes the utility code 'reference-able.'

Upvotes: 2

Related Questions