grafana-jsonnet-refactor
Refactors Grafana Jsonnet dashboards to eliminate duplication and align with available unified libraries while preserving behavior. Use when dashboards contain duplicated code, inconsistent patterns, legacy panel types, or need standardization with existing conventions. Produces single self-contained files without dashboard-specific libraries.
What this skill does
# Grafana Jsonnet Refactor
Eliminate duplication and align existing Jsonnet dashboards with available unified libraries. Preserve behavior while modernizing legacy panels and standardizing patterns.
**Not suitable for**: Initial JSON to Jsonnet conversion (use `grafana-json-to-jsonnet`), content optimization (use `grafana-dashboard-optimize`), or Python report migration (use `grafana-report-to-dashboard`).
## Workflow with progress tracking
Copy this checklist and track your progress:
```
Refactor Progress:
- [ ] Step 1: Read refactor-checklist.md and align with conventions
- [ ] Step 2: Audit dashboard (panels, variables, datasources, patterns)
- [ ] Step 3: Choose refactor mode (direct/wrapper/hybrid)
- [ ] Step 4: Normalize config and shared selectors
- [ ] Step 5: Replace panels with unified constructors
- [ ] Step 6: Organize file structure (imports → config → variables/helpers → panels → rows → dashboard)
- [ ] Step 7: Compile and verify in Grafana
```
**Step 1: Read refactor-checklist.md**
Load `references/refactor-checklist.md` to understand local conventions and standards.
If the dashboard belongs to a specific repo or stack, review the local Jsonnet defaults and docs in the working directory (datasource config, time range, variables, panel types).
**Step 2: Audit the dashboard**
List all panels, variables, datasources, and identify repeated patterns. Note which panels use local helpers vs unified libraries, and whether annotations or dashboard metadata (`__inputs`, `__requires`, `schemaVersion`, `graphTooltip`, `version`) are present.
**Step 3: Choose refactor mode**
Select approach based on dashboard size:
- **Direct migration**: Remove helpers, use unified libs directly (recommended for small dashboards)
- **Wrapper pattern**: Keep helper signatures, call unified libs internally (for large dashboards with many callsites)
- **Hybrid**: Mix approaches where needed
**Step 4: Normalize config and shared selectors**
Extract common configuration (datasource, pluginVersion, timezone, and time range when present) into a `config` object.
**Step 5: Replace panels with unified constructors**
Replace local helpers with `panels.*Panel()` constructors. Apply `standards.*` for units/thresholds and `themes.*` for timeseries styling. Add `id` and `gridPos` via `panels.withIdAndPatches(...)` or `+ { id, gridPos }`.
For styling and table/override patterns, load `references/visual-style-guides.md`.
**Step 6: Organize file structure**
Structure the file: imports → config → constants → variables → selectors/helpers → panel wrappers → panels → rows → annotations → dashboard. Keep all panel definitions as `local` variables in the single file.
**Step 7: Compile and verify**
Run the repo's build/compile script if available. Fix any errors. Verify panel count and layout match the original dashboard in Grafana.
## Guardrails
- Preserve metric semantics and layout intent.
- Avoid broad rewrites; focus on de-duplication and standards alignment.
- Keep a single file; do not create dashboard-specific lib files.
- Only update shared lib files for truly reusable components.
- Do not run `jsonnetfmt` / `jsonnet fmt` on generated Jsonnet files.
## Quality checklist
- [ ] Build/compile succeeds (project script if available).
- [ ] Panel count and layout match the original dashboard.
- [ ] Units and thresholds use `standards.*`.
- [ ] Queries use `prom.*` helpers where applicable.
- [ ] No dashboard-specific lib files exist in final output.
- [ ] `__inputs` / `__requires` and manual import lines preserved when present.
- [ ] Variables return values in Grafana; no duplicate or extra variables.
- [ ] Regex filters preserved or added where needed.
- [ ] Row membership is correct (`gridPos.y` aligns to row `gridPos.y`, and rows include panels).
- [ ] Annotations remain consistent and intentional.
- [ ] Dashboard metadata (`schemaVersion`, `graphTooltip`, `version`) preserved when present.
## Minimal single-file skeleton
```jsonnet
local g = import 'github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet';
local helpers = import '../lib/helpers.libsonnet';
local layouts = import '../lib/layouts.libsonnet';
local panels = import '../lib/panels.libsonnet';
local prom = import '../lib/prometheus.libsonnet';
local standards = import '../lib/standards.libsonnet';
local themes = import '../lib/themes.libsonnet';
// Provisioning mode (real UID). For manual import, switch to ${DS_*}.
local DATASOURCE_UID = '<prometheus-uid>';
// local DATASOURCE_UID = '${DS_PROMETHEUS}';
local config = {
datasource: { type: 'prometheus', uid: DATASOURCE_UID },
pluginVersion: '12.3.0',
};
local qpsStat = panels.statPanel(
title='QPS',
targets=[prom.instantTarget('sum(rate(http_requests_total[1m]))', '')],
datasource=config.datasource,
unit=standards.units.qps,
pluginVersion=config.pluginVersion
);
g.dashboard.new('Dashboard')
+ g.dashboard.withPanels([qpsStat])
```
## References (load as needed)
- `references/visual-style-guides.md`
- `references/full-refactor-playbook.md`
- `references/refactor-checklist.md`
- `references/examples.md`
Related in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.