Kibana: Dashboards as Code
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Checked on 2026-11-09 against Kibana 9.5.x. Tested with Elasticsearch 9.5.6 and Kibana 9.5.6 in the hands-on lab (trial licence): the dashboard definition below, without access_control, was created with PUT in the bookshelf space.
A dashboard built by hand in the browser has the same weaknesses wherever it lives: nobody can review a change before it ships, there is no history except the one the application keeps, a second environment means redoing the work, and the day somebody "improves" it during an incident nobody can say what changed. Treating the dashboard as a file in Git fixes all four, which is the argument made for every kind of observability resource in Observability as Code. This page is the Kibana half for dashboards: the two APIs, the Terraform resource, and how to keep references portable between environments. Alerting resources have their own page (Alerting APIs & Terraform); the Grafana counterpart is Grafana: Dashboards as Code.
Availability
Source: Kibana: Manage dashboards as code.
-
The dashboards-as-code workflow is generally available on Elastic Cloud Serverless and on the Elastic Stack since 9.5 (preview in 9.4). The 9.5.0 release notes record that the Dashboards and Visualizations APIs became generally available with breaking changes to the request and response schemas, so a definition written against a 9.4 preview needs to be revised.
-
The Terraform resource
elasticstack_kibana_dashboardis a technical preview, "still evolving"; its documentation says it may be changed or removed in a future release. -
The data views v2 API (a data view with a chosen ID) is generally available on Serverless and Planned for the Stack; on the Stack 9.0 to 9.5 the existing Data views API accepts an
idin thePOSTbody. -
Creating a dashboard from an AI chat is mentioned only briefly below: Elastic Agent Builder builds dashboards of ES|QL panels from natural language, generally available on Serverless and on the Stack since 9.5 (preview in 9.4), and the Kibana dashboards agent skill (open source, for your own tooling that calls the Dashboards API) is in preview on Serverless and on the Stack since 9.4. Treat the result as a draft to export and review like any other.
The Dashboards API
Source: Kibana: Create dashboards programmatically and Kibana API: Dashboards (the schema is documented in the Dashboards API reference).
The API gives full read and write access to a dashboard: panels, controls, sections and display options, all as inline JSON. Five endpoints, all generally available since 9.5:
| Method and path | Purpose | Notes |
|---|---|---|
|
Search ( |
Returns title, description, tags and metadata, not the panel layout. Filtering by tag name ( |
|
Create |
Returns a generated ID, the full state and metadata. Needs the |
|
Read the complete state |
The source of truth to start a change from. |
|
Upsert: create with that ID if none exists, otherwise replace the whole state |
Returns |
|
Delete |
Permanent. |
Authentication is by API key (Authorization: ApiKey ...) or any other method Kibana accepts; the key’s role needs the All privilege for the Dashboard feature in the space. In a space other than the
default one, prefix the path with /s/<space_id>.
A dashboard document has these top-level fields (only title is required):
-
title,descriptionandtags(tag IDs, not names). -
time_range(from,to, optionalmodeofabsoluteorrelative; date math such asnow-6h) andrefresh_interval(pauseandvaluein milliseconds): the same things as Store time with dashboard. -
query(languageofkqlorluceneandexpression) andfilters(conditions, groups, raw DSL or spatial filters), applied to every panel including pinned ones. -
options: the display settings (use_margins,hide_panel_titles,hide_panel_borders,sync_colors,sync_cursor,sync_tooltips,auto_apply_filters). -
panels: an array whose entries are either a panel (type,gridwithx,y,w,hon the 48-column grid, andconfig) or a collapsible section (title,collapsed,grid.y, nestedpanels). -
pinned_panels: the controls pinned to the top (options_list_control,range_slider_control,time_slider_control,esql_control), up to 100. -
access_control.access_mode:default(all viewers can edit) orwrite_restricted, which needs a caller with a user profile (a request with basic authentication failed with a 500 in the lab). -
esql_approximation, andproject_routing(Serverless cross-project search only).
Panel types with a schema: vis (Lens visualizations, including ES|QL ones), discover_session, markdown, image, links (generally available since 9.5), the controls, the SLO panels (overview, alerts, error budget, burn rate),
the Synthetics panels (stats overview, monitors), the APM service map (generally available since 9.5) and the machine learning and AIOps panels (generally available since 9.5). Panel types without a defined schema, such as Maps,
are not supported yet and return an error on write. The limits are those of the UI: 1,000 top-level items, 1,000 panels per section, 100 pinned controls, and at most 1,000 panels, sections and pinned controls in total.
A vis panel is either by value (the config holds the whole chart, as below) or by reference: config.ref_id points at a Visualizations API object so that one update applies everywhere it is used.
A complete Bookshelf definition
The file below is a trimmed "Bookshelf service health": a pinned control on service.name, a markdown header, the 5xx ratio and request tiles and a latency-style chart written in ES|QL (so no data view is needed), and a collapsed
section. The shapes of the panels follow the examples of the API reference; use the ES|QL fields that Discover shows for your mapping.
{
"title": "Bookshelf service health",
"description": "RED overview of the Bookshelf service (lab)",
"time_range": { "from": "now-6h", "to": "now" },
"refresh_interval": { "pause": false, "value": 30000 },
"query": { "language": "kql", "expression": "" },
"pinned_panels": [
{
"type": "options_list_control",
"width": "medium",
"grow": false,
"config": {
"title": "Service",
"data_view_id": "bookshelf-traces",
"field_name": "service.name"
}
}
],
"panels": [
{
"grid": { "x": 0, "y": 0, "w": 48, "h": 4 },
"type": "markdown",
"config": { "content": "## Bookshelf service health\n\nRunbook: https://wiki.example.com/bookshelf/runbooks" }
},
{
"grid": { "x": 0, "y": 4, "w": 12, "h": 6 },
"type": "vis",
"config": {
"type": "metric",
"title": "Requests",
"data_source": {
"type": "esql",
"query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS requests = COUNT(*)"
},
"metrics": [ { "type": "primary", "column": "requests" } ]
}
},
{
"grid": { "x": 12, "y": 4, "w": 12, "h": 6 },
"type": "vis",
"config": {
"type": "metric",
"title": "5xx ratio",
"data_source": {
"type": "esql",
"query": "FROM traces-* | WHERE @timestamp >= ?_tstart AND @timestamp < ?_tend AND service.name == \"bookshelf\" | STATS errors = COUNT(*) WHERE http.response.status_code >= 500, total = COUNT(*) | EVAL ratio = TO_DOUBLE(errors) / total | KEEP ratio"
},
"metrics": [ { "type": "primary", "column": "ratio" } ]
}
},
{
"grid": { "x": 24, "y": 4, "w": 24, "h": 12 },
"type": "vis",
"config": {
"type": "xy",
"title": "Requests over time",
"layers": [
{
"type": "line",
"data_source": {
"type": "esql",
"query": "FROM traces-* | WHERE service.name == \"bookshelf\" | STATS requests = COUNT() BY BUCKET(@timestamp, 75, ?_tstart, ?_tend)"
},
"x": { "column": "BUCKET(@timestamp, 75, ?_tstart, ?_tend)" },
"y": [ { "column": "requests" } ]
}
],
"axis": { "x": { "title": { "visible": false } } }
}
},
{
"title": "Dependencies",
"collapsed": true,
"grid": { "y": 16 },
"panels": [
{
"grid": { "x": 0, "y": 0, "w": 24, "h": 8 },
"type": "markdown",
"config": { "content": "JVM heap and connection pool panels go here." }
}
]
}
]
}
Reference: the request shape of POST /api/dashboards and the vis ES|QL examples are in the Dashboards API reference
(the metric panel with data_source.type of esql and metrics[].column; the xy panel with a data_source in each layer and BUCKET(@timestamp, 75, ?_tstart, ?_tend) for time-aligned buckets).
The pinned control follows the sections-and-controls example of the reference, which uses a data view ID and a field name. Send it to the lab (below). It was sent to Kibana 9.5.6 with PUT in the bookshelf space and created the dashboard with its pinned control and collapsed section. The
object has no access_control property: the request that included "access_control": { "access_mode": "write_restricted" } failed with a 500 and the server log said that
Kibana could not determine the user profile ID of the caller (the call used basic authentication), because a write-restricted dashboard needs an identifiable user profile.
Deploying with PUT and chosen IDs
Source: Kibana: Manage dashboards as code (keep references portable across environments).
POST generates a new ID every time, so running it twice creates two dashboards. Use PUT with an ID you choose, and the same command creates the dashboard the first time and replaces it afterwards:
curl -X PUT "${KIBANA_URL}/s/bookshelf/api/dashboards/bookshelf-service-health" \
-H "Authorization: ApiKey ${API_KEY}" \
-H "kbn-xsrf: true" \
-H "Content-Type: application/json" \
-d @dashboards/bookshelf-service-health.json
Reference: Kibana API: Dashboards (PUT /api/dashboards/{id}). Because PUT replaces the complete state, edit the file in Git, not the live dashboard: anything changed in the UI is overwritten at the next
deployment, and that is the point. To make a targeted change to a dashboard that only exists in Kibana, GET it, change the JSON and PUT the whole object back. The same applies to
PUT /api/visualizations/{id} for library visualizations (Visualizations API, generally available since 9.5), whose objects a dashboard embeds with a vis panel whose config.ref_id is the visualization ID.
The portable ID problem. Dashboards and the objects they reference (data views, library visualizations) are matched by ID. Auto-generated IDs differ between environments, so a freshly deployed panel can show no data because the reference does not resolve. The documentation lists three approaches, from most to least automated:
-
Terraform: the provider tracks each resource and maps IDs per environment.
-
ES|QL panels: the definition names the indices in the query, so it needs no external data view or library visualization (as in the example above, apart from the control); panels that cannot use ES|QL can be defined by value and backed by an ad hoc data view (
data_view_specwithindex_patternandtime_field, as in the API examples). -
Matching IDs: give every referenced object the same ID in every environment. A data view can get a chosen ID in the UI (Custom data view ID) or through the API: on Serverless with the data views v2 API, on the Stack 9.0 to 9.5 by passing an
idin thePOSTbody of the Data views API. Use readable IDs such asbookshelf-traces.
curl -X POST "${KIBANA_URL}/s/bookshelf/api/data_views/data_view" \
-H "Authorization: ApiKey ${API_KEY}" -H "kbn-xsrf: true" -H "Content-Type: application/json" \
-d '{"data_view":{"id":"bookshelf-traces","name":"Bookshelf traces","title":"traces-*","timeFieldName":"@timestamp"}}'
Reference: Kibana API: Data views (create a data view; the documentation example sends title and name, and the Dashboards-as-code page states that the Stack accepts id in the same request).
To deploy into another space of the same cluster, put that space ID in the request path; the JSON export flow can open a pre-filled request in Dev Tools Console where you can set the destination space.
Terraform
Source: Kibana: Automate with Terraform and the provider documentation of
elasticstack_kibana_dashboard and
elasticstack_kibana_data_view (source in the
provider repository).
The elastic/elasticstack provider (the documentation uses the ~> 0.16 constraint) manages dashboards through the Dashboards API. It is a technical preview, so pin the provider version and read its changelog before upgrading. A Terraform dashboard is
written in the provider’s own schema, not in the API’s JSON, and the two are not interchangeable: exported dashboard JSON does not map to the resource, so Terraform suits dashboards that are authored as code from the start. An existing dashboard
can be brought under management with terraform import, but you write the matching configuration by hand, and the resource does not yet expose every panel type or dashboard-level option of the API: check the coverage before adopting it. Only title is
required; dashboard_id set explicitly makes the create use the upsert semantics, space_id selects the space, and time_range, refresh_interval and query are optional (removing the block clears it in Kibana).
terraform {
required_providers {
elasticstack = {
source = "elastic/elasticstack"
version = "~> 0.16"
}
}
}
provider "elasticstack" {
kibana {} # endpoints and credentials from the provider environment variables
}
resource "elasticstack_kibana_data_view" "traces" {
data_view = {
id = "bookshelf-traces"
name = "Bookshelf traces"
title = "traces-*"
time_field_name = "@timestamp"
}
}
resource "elasticstack_kibana_dashboard" "bookshelf_service_health" {
dashboard_id = "bookshelf-service-health"
title = "Bookshelf service health"
description = "RED overview of the Bookshelf service (lab)"
tags = []
time_range = { from = "now-6h", to = "now" }
refresh_interval = { pause = false, value = 30000 }
query = { language = "kql", expression = "" }
panels = [
{
type = "markdown"
grid = { x = 0, y = 0, w = 48, h = 4 }
markdown_config = {
by_value = {
content = "## Bookshelf service health"
settings = { open_links_in_new_tab = true }
}
}
},
{
type = "vis"
grid = { x = 0, y = 4, w = 12, h = 6 }
vis_config = {
by_value = {
metric_chart_config = {
data_source_json = jsonencode({
type = "data_view_spec"
index_pattern = "traces-*"
time_field = "@timestamp"
})
query = { expression = "service.name : \"bookshelf\"" }
metrics = [{
config_json = jsonencode({
type = "primary"
operation = "count"
format = { type = "number" }
})
}]
}
}
}
}
]
}
Reference: the two panel shapes are adapted from the "Example Usage" of the
elasticstack_kibana_dashboard documentation (markdown by_value with settings, and the typed vis_config.by_value.metric_chart_config), and the data view from
the elasticstack_kibana_data_view documentation, which includes a data view with id. The query expression in the metric panel is
KQL. The provider’s guides (getting started with the layout grid and Lens metric, line, bar and donut panels; pinned controls, KPI rows and tables; collapsible sections, ES|QL controls and access control)
are the next step; the registry page is the place to check the newest attributes.
Which route to choose: JSON through the API when the dashboards are built in the UI and exported (the shortest path, and the only one that covers everything the API supports), Terraform when the platform is already managed by Terraform and you want one plan for data views, dashboards, rules and connectors (see the state and workflow pages of Terraform). Mixing both for the same dashboard is asking for the next apply to undo the last pipeline run.
A Git workflow
Source: Kibana: workflow (export, store, review, deploy).
-
Export. Build or change the dashboard in a development space, then Export > Export JSON (Serverless, and the Stack in the preview of 9.4 and 9.5 and generally available in 9.6+; before 9.4, export NDJSON from Saved Objects instead and use the saved objects workflow of Sharing, Reporting & Saved Objects). The flow can open the request in Dev Tools Console.
-
Store. Commit the file to
dashboards/bookshelf-service-health.jsonwith the chosen ID in the file name. Format it consistently (sorted keys, two spaces) so that a diff shows a change and not noise. -
Review. The pull request diffs the structured JSON. Review
query,filtersand thresholds as carefully as code: a changed threshold on a "5xx ratio" tile is an operational change. -
Deploy. CI runs the
PUTfor each file against each environment’s space, with an API key held as a CI secret, and fails the build on a non-2xx response. Re-running is safe becausePUTis an upsert. -
Protect the result. Deploy as a caller that has a user profile (basic authentication failed in the lab) with
access_control.access_modeset towrite_restricted(or Can view for readers), so that the UI is not an alternative way of changing production.
Roll back by reverting the commit and running the pipeline. If the target Kibana moves to a new minor version, redeploy and read the validation messages: a schema that changed since the preview is the usual reason.
Verifying in the lab
-
Create the data view
bookshelf-traceswith thecurlabove, thenPUTthe JSON file. A201means it was created; run it again and expect200. -
Open "Bookshelf service health", start the load generator and confirm that the tiles and the chart draw; change the title in the UI, run the
PUTagain and watch the change disappear. -
GET /api/dashboards/bookshelf-service-healthand diff the response with your file: Kibana fills in defaults foroptionsand panelidvalues, which tells you what the minimal definition may leave out. -
Optional, with Terraform: apply the HCL, run
terraform planagain and expect no changes, then edit the panel in the UI and see the drift in the plan.
Things that go wrong
-
A
PUTremoved my panels: it is a full replacement; send the complete state, starting from aGETif you do not hold the file. -
Panels show "no data" in the new environment: a data view or library visualization ID does not exist there; use ES|QL panels, chosen IDs or Terraform.
-
The write fails for a panel: the panel type has no schema in the API yet (Maps, for example), or the 9.4 preview shape was used against the 9.5 schema.
-
Terraform wants to recreate the dashboard: changing
dashboard_idforces replacement; and whatever the technical preview resource does not model is not managed. -
The deployed dashboard differs from Git a day later: someone edited it in the UI; use
write_restrictedand a drift check (GETand diff) in CI. -
Limits: more than 1,000 items, or 100 pinned controls, is rejected with a validation error.
In the books
Shah (Kibana 8.x Quick Start Guide, chapter 8) suggests downloading a workpad as JSON and keeping Kibana JSON in Git for version control, rollbacks and scripted deployments, which is the idea of this page, but for the Canvas workpad of Kibana 8.x and with manual downloads. The other Kibana books provided do not cover it. For Grafana, McCollam (chapter 13) and Chapman and Holmes (chapter 10) treat provisioning and Terraform, which is the comparison made in Observability as Code. What has changed: Kibana now has a supported, generally available API for dashboards and visualizations (9.5) and a (preview) Terraform resource, so a dashboard no longer has to travel as an opaque saved-object export.