grafana / grafonnet-lib

Jsonnet library for generating Grafana dashboard files.
https://grafana.github.io/grafonnet-lib/
Apache License 2.0
1.08k stars 217 forks source link

How to load set of panels from other file #298

Closed aliaksei-karneyeu closed 3 years ago

aliaksei-karneyeu commented 3 years ago

Hello guys, I'm working with grafonnet for some and and quiet like it, thank you for your work.

Currently I'm working on case, where I need to have common set of panels in different dashboards. So I created file common_panels.jibsonnet:

local grafana = import 'grafonnet/grafana.libsonnet';
local show_metrics(title,expr) = {
  grafana.graphPanel.new(
    title=title+' cpu',
  )
  .addTarget(
    grafana.prometheus.target(
      expr=expr,
    )
  )
    grafana.graphPanel.new(
    title=title+' ram',,
  )
  .addTarget(
    grafana.prometheus.target(
      expr=expr,
    )
  )
  }

and on main file I would like to call it with needed parameters like:

local grafana = import 'grafonnet/grafana.libsonnet';
local common_metrics = import 'common_panels.jibsonnet';
grafana.dashboard.new(
  title='My dashboard',
  time_from='now-1h',
  editable='true',
)
.addRow(
  grafana.row.new(title='General metrics')
    common_metrics.show_metrics('My title','sum(rate(...))')
)

Unfortunatelly I couldn't make it work. One thing that could work - to create json objects in the function, so file common_panels.jibsonnet would be muuuuuch longer then main file.

trotttrotttrott commented 3 years ago

Hi! First, in your main file, you'll need to call addPanel to get the show_metrics return value in the right place.

...
.addRow(
  grafana.row.new(title='General metrics')
  .addPanel(
    common_metrics.show_metrics('My title', 'sum(rate(...))')
  )
)

Then define show_metrics like this:

...
{
  show_metrics(title, expr)::
    grafana.graphPanel.new(title)
    .addTarget(
      grafana.prometheus.target(expr)
    ),
}

Functions defined with local are not accessible outside of the file they're defined in.

aliaksei-karneyeu commented 3 years ago

Thank you. It works