Kibana: Alerting APIs & Terraform
|
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 connector, rule, SLO, burn rate rule and maintenance window requests ran against the lab, and the HCL passes terraform validate with provider 0.16.6 (it was not applied).
Rules built by clicking are fine for exploring and fatal for operating: nobody can review them, rebuild them in another environment or tell
who changed the threshold last Tuesday. Kibana has a documented REST API for rules, connectors, maintenance windows and SLOs, and the
elastic/elasticstack Terraform provider wraps the same endpoints as resources, so the alerting setup of a service can live in Git beside
its code. This page shows both routes for the complete Bookshelf set: one webhook connector, a 5xx ratio rule, a p95 latency rule, a no-data
rule, an error-log rule, an SLO with its burn rate rule and a maintenance window. The general argument for monitoring configuration as
code is on Observability as Code; the Kibana dashboards equivalent is
Dashboards as Code; Terraform in general is under
Terraform; the Grafana equivalent is
Grafana: Provisioning Alerting Resources. What the rules mean is on
Observability Rules; the setup and security model (API keys, privileges) is on
Alerting Setup, Security & Scaling.
Conventions of the Kibana API
-
Authentication: an API key (
Authorization: ApiKey <encoded value>) or basic authentication (Authorization: Basic <base64 of user:password>; curl’s-udoes this). Both are documented for the endpoints on this page. Rules created through the API are owned by the API key or user that made the call, which is the same ownership rule as in the UI. -
CSRF header: every call that writes needs
kbn-xsrf: true; without it Kibana answers with an error. -
Spaces: every endpoint has a space variant,
/s/<space-id>/api/...; without the prefix the call goes to the default space. Rules and connectors belong to one space, so use thebookshelfspace path throughout. -
Client-chosen identifiers: the rule and connector
POSTendpoints take the identifier in the path (POST /api/alerting/rule/{id},POST /api/actions/connector/{id}); if it is omitted a random one is generated. A fixed id makes scripts idempotent: a repeated create answers409(rule id already in use), and the script then switches toPUT. -
Immutability:
PUTon a rule updates the name, schedule, parameters, actions, tags and the other settings, but notrule_type_id,consumerorenabled; enabling and disabling are separate endpoints, and a changed rule type means delete and create. APUTreplaces theactionsarray, so an update that omits actions removes them.
The documentation of the Kibana API itself is generated from its OpenAPI specification; the page for each operation lists its parameters, and the specification can be downloaded from the same site.
The endpoints that matter
| Area | Endpoints | Page |
|---|---|---|
Alerting framework |
|
|
Rules |
|
same group |
Snooze |
|
same group |
Backfill |
|
same group |
Connectors |
|
|
Maintenance windows |
|
|
SLOs |
|
The alerting group has 23 operations and no bulk operations: to change many rules, _find them (with search, search_fields, filter, fields,
per_page and page) and loop. Snoozing, maintenance windows and flapping, which decide whether an alert produces a notification, are explained on
Alert Lifecycle, Snooze & Maintenance Windows.
Setup for the examples
The lab assumes the space bookshelf, the user alice (role bookshelf-sre) from
Spaces, Roles & Privileges, the data views bookshelf-traces (traces-*) and
bookshelf-logs created in
Data Views & Discover and the webhook receiver. In production use a
service user or API key owned by CI instead of a person, for the reasons given on the setup page.
export KIBANA="http://localhost:5601/s/bookshelf"
export KAUTH="alice:change-me-lab-only"
api() { curl -sS -u "$KAUTH" -H "kbn-xsrf: true" -H "Content-Type: application/json" "$@"; }
The connector
The webhook connector is the receiver of all lab alerts. It is created with a fixed id so that rules can refer to it. The connector posts to
http://webhook-receiver:8080/kibana; if xpack.actions.allowedHosts is set, the host webhook-receiver must be in it.
api -X POST "$KIBANA/api/actions/connector/bookshelf-webhook" -d '{
"name": "bookshelf-webhook",
"connector_type_id": ".webhook",
"config": {
"url": "http://webhook-receiver:8080/kibana",
"method": "post",
"hasAuth": false,
"headers": { "Content-Type": "application/json" }
}
}'
The request body has name, connector_type_id, config and secrets (the webhook has none here because it uses no authentication; with
basic authentication the user and password go in secrets, which Kibana stores encrypted with the key from the setup page).
Test it without a rule through the execute endpoint, whose params are the connector’s action parameters (the webhook’s is a body):
api -X POST "$KIBANA/api/actions/connector/bookshelf-webhook/_execute" \
-d '{ "params": { "body": "{\"rule\":\"manual test\",\"status\":\"test\"}" } }'
The webhook connector’s method is post or put in the API specification of 9.5 (the connector page lists more methods since 9.3 and OAuth 2.0
authentication since 9.2); the connector concepts are on Connectors.
Reference: Create a connector, Run a connector, Webhook connector.
Rule actions and the action group
A rule action names a connector id, the params for it (templated with Mustache variables), the group that triggers it and a frequency. The
group must be one of the rule type’s action groups, which GET /api/alerting/rule_types lists with the available variables; a wrong group is rejected
with 400. For the rule types used here:
| Rule type id | Action groups | Notes |
|---|---|---|
|
|
Variables include |
|
|
Variables include |
|
|
Each burn rate window names its action group. |
The custom threshold group ids come from the Kibana source (the constants of the custom threshold rule), and the documentation page of the rule names the
groups as Alert, Warning, No Data and Recovered; confirm the ids on your version with GET /api/alerting/rule_types. The frequency object has
notify_when (onActionGroupChange, onActiveAlert or onThrottleInterval), summary (one notification for all alerts of a run instead of
one per alert) and throttle (only with onThrottleInterval). The older rule-level notify_when and throttle are deprecated since 8.13, cannot be used
together with action-level frequency and are converted when you edit the rule in the UI. The lab uses onActionGroupChange: one message when an
alert fires, one when it recovers. The model of actions, frequencies and variables is on
Actions, Frequency & Action Variables.
The two actions used by every custom threshold rule below, written once and injected with jq. The webhook body is a JSON string, so the Mustache
variables sit inside a string; Kibana escapes variable values so the final JSON stays valid:
cat > actions-ct.json <<'JSON'
[
{
"id": "bookshelf-webhook",
"group": "custom_threshold.fired",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"{{alert.actionGroupName}}\",\"reason\":\"{{context.reason}}\",\"link\":\"{{context.alertDetailsUrl}}\"}" }
},
{
"id": "bookshelf-webhook",
"group": "recovered",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"{{alert.actionGroupName}}\",\"alert\":\"{{alert.id}}\"}" }
}
]
JSON
Rule 1: the 5xx ratio
The first rule is the symptom that matters most to users: the share of requests that fail with a server error over 5 minutes, above 0.05 (5
percent). A custom threshold rule expresses a ratio as two aggregations (A counts the 5xx requests with a KQL filter, B counts all requests) and the
equation A / B (the per-aggregation filter is Stack 9.4 and later). noDataBehavior is one of recover, remainActive or alertOnNoData
(Stack 9.4 and later; the older boolean alertOnNoData also exists in the schema). The artifacts object attaches an investigation guide and the dashboard
to the rule (write support from Stack 9.1; the guide shows on the alert details page, see
Alert Lifecycle, Snooze & Maintenance Windows). The consumer
alerts is the role visibility "All"; check authorized_consumers in the rule types response if Kibana rejects it.
cat > rule-5xx.json <<'JSON'
{
"name": "Bookshelf 5xx ratio above 5 percent",
"rule_type_id": "observability.rules.custom_threshold",
"consumer": "alerts",
"schedule": { "interval": "1m" },
"tags": ["bookshelf", "lab"],
"params": {
"searchConfiguration": {
"index": "bookshelf-traces",
"query": { "language": "kuery", "query": "service.name : \"bookshelf\"" }
},
"criteria": [
{
"aggType": "custom",
"metrics": [
{ "name": "A", "aggType": "count", "filter": "http.response.status_code >= 500" },
{ "name": "B", "aggType": "count" }
],
"equation": "A / B",
"label": "5xx ratio",
"comparator": ">",
"threshold": [0.05],
"timeSize": 5,
"timeUnit": "m"
}
],
"noDataBehavior": "recover"
},
"artifacts": {
"investigation_guide": { "blob": "Check the Bookshelf service health dashboard, then the errors in Discover. Runbook: https://wiki.example.com/bookshelf/runbooks" },
"dashboards": [ { "id": "bookshelf-service-health" } ]
}
}
JSON
jq --argjson actions "$(cat actions-ct.json)" '.actions = $actions' rule-5xx.json \
| api -X POST "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio" -d @-
The response is the stored rule: id, enabled (true unless you send enabled: false), api_key_owner (the user whose privileges the rule runs
with), next_run, execution_status and last_run. A 409 means the id exists. The fields http.response.status_code and service.name are
the ones used in the Lens examples of this section; use the field names Discover shows for your data, since the OpenTelemetry mapping of the lab
can differ (see Ingesting Monitoring Data).
Reference: Create a rule (response, 409 for an id in use),
Custom threshold rule; the parameters follow the
custom threshold schema in the Kibana 9.5 OpenAPI specification.
Rules 2 and 3: p95 latency and no data
The latency rule alerts when the 95th percentile of the request duration passes 0.5 s. The lab’s setup.sh uses the APM latency threshold rule
(apm.transaction_duration, 95th percentile) for this; the request below builds the same condition as a custom threshold rule instead. The aggregation p95 is available on the custom rule’s metrics;
the unit is the field’s, so a duration in microseconds (the APM transaction duration field transaction.duration.us) is compared with 500000.
alert_delay makes the alert occur only after the given number of consecutive runs met the condition; with warningComparator and warningThreshold
(Stack 9.5 and later) the rule also has a warning level.
cat > rule-p95.json <<'JSON'
{
"name": "Bookshelf p95 latency above 0.5 s",
"rule_type_id": "observability.rules.custom_threshold",
"consumer": "alerts",
"schedule": { "interval": "1m" },
"tags": ["bookshelf", "lab"],
"alert_delay": { "active": 2 },
"params": {
"searchConfiguration": {
"index": "bookshelf-traces",
"query": { "language": "kuery", "query": "service.name : \"bookshelf\" and transaction.type : \"request\"" }
},
"criteria": [
{
"aggType": "custom",
"metrics": [ { "name": "A", "aggType": "p95", "field": "transaction.duration.us" } ],
"equation": "A",
"label": "p95 duration (us)",
"comparator": ">",
"threshold": [500000],
"warningComparator": ">",
"warningThreshold": [400000],
"timeSize": 5,
"timeUnit": "m"
}
],
"noDataBehavior": "recover"
}
}
JSON
jq --argjson actions "$(cat actions-ct.json)" '.actions = $actions' rule-p95.json \
| api -X POST "$KIBANA/api/alerting/rule/bookshelf-p95-latency" -d @-
The no-data alert is the one that catches the failure the other rules cannot see: a service that stops reporting produces no failing requests. Its
condition counts requests and asks for fewer than one in 5 minutes, and its no-data behavior is alertOnNoData, which creates an alert when
the data itself is missing. A no-data alert belongs to the action group custom_threshold.nodata, which the two shared actions do not cover, so the command below
adds a third action for that group (the same webhook with the same body as the fired action).
cat > rule-nodata.json <<'JSON'
{
"name": "Bookshelf stopped reporting requests",
"rule_type_id": "observability.rules.custom_threshold",
"consumer": "alerts",
"schedule": { "interval": "1m" },
"tags": ["bookshelf", "lab"],
"params": {
"searchConfiguration": {
"index": "bookshelf-traces",
"query": { "language": "kuery", "query": "service.name : \"bookshelf\"" }
},
"criteria": [
{
"aggType": "custom",
"metrics": [ { "name": "A", "aggType": "count" } ],
"equation": "A",
"label": "requests",
"comparator": "<",
"threshold": [1],
"timeSize": 5,
"timeUnit": "m"
}
],
"noDataBehavior": "alertOnNoData"
}
}
JSON
jq --argjson actions "$(cat actions-ct.json)" \
'.actions = ($actions + [$actions[0] | .group = "custom_threshold.nodata"])' rule-nodata.json \
| api -X POST "$KIBANA/api/alerting/rule/bookshelf-no-data" -d @-
Reference: Custom threshold rule (no-data
behaviors and the warning threshold), the alert_delay property of the Create a rule API.
Rule 4: error logs
The error-log spike rule is an Elasticsearch query rule on the logs data view: it counts documents that match a KQL query in the last 5 minutes and fires above
20. excludeHitsFromPreviousRun avoids counting the same document in consecutive runs, and groupBy: all means one alert for the whole query.
api -X POST "$KIBANA/api/alerting/rule/bookshelf-error-log-spike" -d '{
"name": "Bookshelf error log spike",
"rule_type_id": ".es-query",
"consumer": "alerts",
"schedule": { "interval": "1m" },
"tags": ["bookshelf", "lab"],
"params": {
"searchType": "searchSource",
"searchConfiguration": {
"index": "bookshelf-logs",
"query": { "language": "kuery", "query": "service.name : \"bookshelf\" and severity_text : \"ERROR\"" }
},
"timeField": "@timestamp",
"aggType": "count",
"groupBy": "all",
"excludeHitsFromPreviousRun": true,
"size": 100,
"threshold": [20],
"thresholdComparator": ">",
"timeWindowSize": 5,
"timeWindowUnit": "m"
},
"actions": [
{
"id": "bookshelf-webhook",
"group": "query matched",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"value\":\"{{context.value}}\",\"link\":\"{{context.link}}\"}" }
},
{
"id": "bookshelf-webhook",
"group": "recovered",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"recovered\"}" }
}
]
}'
The documented examples of the query rule are for the DSL, KQL and ES|QL variants (searchType esQuery, searchSource and esqlQuery); the KQL example of the
documentation omits timeField, which the data view usually supplies; keep it if Kibana asks. The rule is explained on
Rules & Stack Rule Types.
Reference: Create a rule (examples createEsQueryKqlRuleRequest and createEsQueryRuleRequest).
Rule 5: the SLO and its burn rate
An SLO and its burn rate rule are created in this order, because the rule refers to the SLO’s id. The SLO accepts an optional id of 8 to 36 characters, so
the script can fix it (the SLO types and the transforms underneath are on SLOs). The APM availability SLI (sli.apm.transactionErrorRate, latency sli.apm.transactionDuration) reads APM-shaped metric indices; the lab’s OpenTelemetry data lands in
traces-* data streams, and the APM indicator over metrics-* returned an SLI of 1 with a burn rate of 400 regardless of the failures, so the lab SLO uses the custom KQL
indicator on the trace documents, which was verified to move with the failure rate.
api -X POST "$KIBANA/api/observability/slos" -d '{
"id": "bookshelf-availability",
"name": "Bookshelf availability",
"description": "99.5 percent of requests succeed over 30 days",
"indicator": {
"type": "sli.kql.custom",
"params": {
"index": "traces-*",
"timestampField": "@timestamp",
"filter": "service.name : \"bookshelf\"",
"good": "http.response.status_code < 500",
"total": "http.response.status_code : *"
}
},
"timeWindow": { "duration": "30d", "type": "rolling" },
"budgetingMethod": "occurrences",
"objective": { "target": 0.995 },
"tags": ["bookshelf", "lab"]
}'
The burn rate rule has sloId and windows. Each window has a stable id, a burnRateThreshold, a longWindow, a shortWindow (one twelfth of the long one, which the UI
also uses), the actionGroup it triggers and optionally maxBurnRateThreshold; both windows must exceed the threshold for the alert to fire. The four
windows below are 1 hour at 14.4, 6 hours at 6, 24 hours at 3 and 72 hours at 1, as in the SLO page; the rule needs an action per group it should notify
on (here the critical and high groups page, the others are left for dashboards). The consumer of the rule is slo.
api -X POST "$KIBANA/api/alerting/rule/bookshelf-slo-burn-rate" -d '{
"name": "Bookshelf availability burn rate",
"rule_type_id": "slo.rules.burnRate",
"consumer": "slo",
"schedule": { "interval": "1m" },
"tags": ["bookshelf", "lab"],
"params": {
"sloId": "bookshelf-availability",
"windows": [
{ "id": "w-1h", "burnRateThreshold": 14.4, "longWindow": { "value": 1, "unit": "h" }, "shortWindow": { "value": 5, "unit": "m" }, "actionGroup": "slo.burnRate.alert" },
{ "id": "w-6h", "burnRateThreshold": 6, "longWindow": { "value": 6, "unit": "h" }, "shortWindow": { "value": 30, "unit": "m" }, "actionGroup": "slo.burnRate.high" },
{ "id": "w-24h", "burnRateThreshold": 3, "longWindow": { "value": 24, "unit": "h" }, "shortWindow": { "value": 2, "unit": "h" }, "actionGroup": "slo.burnRate.medium" },
{ "id": "w-72h", "burnRateThreshold": 1, "longWindow": { "value": 72, "unit": "h" }, "shortWindow": { "value": 6, "unit": "h" }, "actionGroup": "slo.burnRate.low" }
]
},
"actions": [
{
"id": "bookshelf-webhook", "group": "slo.burnRate.alert",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"critical burn\",\"reason\":\"{{context.reason}}\",\"link\":\"{{context.alertDetailsUrl}}\"}" }
},
{
"id": "bookshelf-webhook", "group": "slo.burnRate.high",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"high burn\",\"reason\":\"{{context.reason}}\"}" }
},
{
"id": "bookshelf-webhook", "group": "recovered",
"frequency": { "notify_when": "onActionGroupChange", "summary": false },
"params": { "body": "{\"rule\":\"{{rule.name}}\",\"status\":\"recovered\"}" }
}
]
}'
Reference: Create an SLO,
SLO burn rate rule; the rule parameters are those of the
slo.rules.burnRate schema of the Kibana 9.5 OpenAPI specification and the group ids are the constants of the SLO plugin in the Kibana source.
Managing rules after creation
api "$KIBANA/api/alerting/rules/_find?search=bookshelf&search_fields=name&per_page=20&fields=name&fields=enabled" # list
api "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio" # read
api -X POST "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio/_disable" # disable
api -X POST "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio/_enable" # enable
api -X POST "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio/snooze_schedule" -d '{
"schedule": { "custom": { "duration": "24h", "start": "2026-11-10T08:00:00.000Z", "timezone": "UTC" } }
}'
api "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio/query_inspector" # the Elasticsearch query it runs
api -X DELETE "$KIBANA/api/alerting/rule/bookshelf-5xx-ratio" # delete
A snooze schedule has a duration (d, h, m or s), a start in ISO 8601 UTC, a time zone and optionally a recurring object (every, end,
occurrences, onWeekDay, onMonthDay, onMonth); disabling a rule stops evaluation, whereas muting or snoozing keeps evaluating
but suppresses actions. To update in a pipeline, PUT the whole definition (without rule_type_id, consumer and enabled) and note that the edit gives the rule a new
API key owned by the calling identity.
Maintenance windows
A maintenance window suppresses notifications for the alerts that match its scope while it is active; the alerts are still created. It is GA since 9.2 according to the page metadata (preview in 9.0 and 9.1), and the scope is a KQL filter over the alert documents, replacing the rule categories of earlier versions. The window below covers a weekly deploy slot of the Bookshelf rules:
api -X POST "$KIBANA/api/maintenance_window" -d '{
"title": "Bookshelf weekly deploy",
"enabled": true,
"schedule": {
"custom": {
"start": "2026-11-15T22:00:00.000Z",
"duration": "1h",
"timezone": "UTC",
"recurring": { "every": "1w", "onWeekDay": ["SU"] }
}
},
"scope": { "alerting": { "query": { "kql": "kibana.alert.rule.tags : \"bookshelf\"" } } }
}'
The duration is <integer><unit> with d, h, m or s, recurring.every uses d, w, M or y, onWeekDay takes MO to SU or an ordinal
such as +1MO, and recurring can be bounded with end or occurrences. The call needs the Maintenance Windows feature privilege, and some rule types are
not affected by the filter (Stack Monitoring, tracking containment, anomaly detection job health, transform health).
Reference: Create a maintenance window.
Terraform
The elastic/elasticstack provider (the documentation pins ~> 0.16; the GitHub release feed shows pseudo-version tags, so pin the constraint the
documentation shows and read the changelog before upgrading) has the resources
elasticstack_kibana_action_connector, elasticstack_kibana_alerting_rule, elasticstack_kibana_maintenance_window and elasticstack_kibana_slo, each with
a space_id argument (the default space if omitted) and a kibana_connection block to override the provider’s. The provider reads Kibana credentials from
the kibana block or from KIBANA_ENDPOINT, KIBANA_USERNAME, KIBANA_PASSWORD, KIBANA_API_KEY or KIBANA_BEARER_TOKEN, and falls back to the Elasticsearch
credentials; an API key for alerting rules needs Stack 8.8 or later.
terraform {
required_version = ">= 1.0.0"
required_providers {
elasticstack = {
source = "elastic/elasticstack"
version = "~> 0.16"
}
}
}
provider "elasticstack" {
kibana {
endpoints = ["http://localhost:5601"]
username = "alice"
password = var.kibana_password
}
}
variable "kibana_password" {
type = string
sensitive = true
}
locals {
space_id = "bookshelf"
webhook_body = "{\"rule\":\"{{rule.name}}\",\"status\":\"{{alert.actionGroupName}}\",\"reason\":\"{{context.reason}}\",\"link\":\"{{context.alertDetailsUrl}}\"}"
}
resource "elasticstack_kibana_action_connector" "bookshelf_webhook" {
space_id = local.space_id
name = "bookshelf-webhook"
connector_type_id = ".webhook"
connector_id = "9a3f2b64-5c1e-4d7a-8f20-6b1d3c4e5a70" # a UUID v1 or v4, fixed so that plans are stable
config = jsonencode({
url = "http://webhook-receiver:8080/kibana"
method = "post"
hasAuth = false
headers = { "Content-Type" = "application/json" }
})
}
The resource documents connector_id as a UUID v1 or v4 (the API itself accepts 1 to 36 characters, which is why the curl example above can use
bookshelf-webhook), config and secrets as JSON strings, and write-only secrets_wo with secrets_wo_version (Terraform 1.11 and later) to keep secrets out of the state. Rules
take params and each action’s params as JSON strings too. The three custom threshold rules, driven from one map and with the two actions generated
by a dynamic block:
locals {
custom_threshold_rules = {
"bookshelf-5xx-ratio" = {
name = "Bookshelf 5xx ratio above 5 percent"
query = "service.name : \"bookshelf\""
nodata = "recover"
criteria = [{
aggType = "custom"
metrics = [
{ name = "A", aggType = "count", filter = "http.response.status_code >= 500" },
{ name = "B", aggType = "count" }
]
equation = "A / B"
label = "5xx ratio"
comparator = ">"
threshold = [0.05]
timeSize = 5
timeUnit = "m"
}]
}
"bookshelf-p95-latency" = {
name = "Bookshelf p95 latency above 0.5 s"
query = "service.name : \"bookshelf\" and transaction.type : \"request\""
nodata = "recover"
criteria = [{
aggType = "custom"
metrics = [{ name = "A", aggType = "p95", field = "transaction.duration.us" }]
equation = "A"
label = "p95 duration (us)"
comparator = ">"
threshold = [500000]
warningComparator = ">"
warningThreshold = [400000]
timeSize = 5
timeUnit = "m"
}]
}
"bookshelf-no-data" = {
name = "Bookshelf stopped reporting requests"
query = "service.name : \"bookshelf\""
nodata = "alertOnNoData"
criteria = [{
aggType = "custom"
metrics = [{ name = "A", aggType = "count" }]
equation = "A"
label = "requests"
comparator = "<"
threshold = [1]
timeSize = 5
timeUnit = "m"
}]
}
}
}
resource "elasticstack_kibana_alerting_rule" "custom_threshold" {
for_each = local.custom_threshold_rules
space_id = local.space_id
rule_id = each.key
name = each.value.name
consumer = "alerts"
rule_type_id = "observability.rules.custom_threshold"
interval = "1m"
enabled = true
tags = ["bookshelf", "lab"]
params = jsonencode({
searchConfiguration = {
index = "bookshelf-traces"
query = { language = "kuery", query = each.value.query }
}
criteria = each.value.criteria
noDataBehavior = each.value.nodata
})
dynamic "actions" {
for_each = ["custom_threshold.fired", "recovered"]
content {
group = actions.value
id = elasticstack_kibana_action_connector.bookshelf_webhook.connector_id
params = jsonencode({ body = local.webhook_body })
frequency {
summary = false
notify_when = "onActionGroupChange"
}
}
}
}
The error-log rule, the SLO with its burn rate rule and the maintenance window follow the same pattern. The SLO resource has one indicator block per type
(apm_availability_indicator, apm_latency_indicator, kql_custom_indicator, metric_custom_indicator, histogram_custom_indicator, timeslice_metric_indicator),
a slo_id that can be fixed, time_window, budgeting_method and objective blocks and optional settings. The maintenance window resource requires
custom_schedule with a recurring attribute and puts the KQL in scope.alerting.kql:
resource "elasticstack_kibana_alerting_rule" "error_logs" {
space_id = local.space_id
rule_id = "bookshelf-error-log-spike"
name = "Bookshelf error log spike"
consumer = "alerts"
rule_type_id = ".es-query"
interval = "1m"
tags = ["bookshelf", "lab"]
params = jsonencode({
searchType = "searchSource"
searchConfiguration = {
index = "bookshelf-logs"
query = { language = "kuery", query = "service.name : \"bookshelf\" and severity_text : \"ERROR\"" }
}
timeField = "@timestamp"
aggType = "count"
groupBy = "all"
excludeHitsFromPreviousRun = true
size = 100
threshold = [20]
thresholdComparator = ">"
timeWindowSize = 5
timeWindowUnit = "m"
})
dynamic "actions" {
for_each = ["query matched", "recovered"]
content {
group = actions.value
id = elasticstack_kibana_action_connector.bookshelf_webhook.connector_id
params = jsonencode({ body = "{\"rule\":\"{{rule.name}}\",\"status\":\"{{alert.actionGroupName}}\"}" })
frequency {
summary = false
notify_when = "onActionGroupChange"
}
}
}
}
resource "elasticstack_kibana_slo" "availability" {
space_id = local.space_id
slo_id = "bookshelf-availability"
name = "Bookshelf availability"
description = "99.5 percent of requests succeed over 30 days"
budgeting_method = "occurrences"
tags = ["bookshelf", "lab"]
kql_custom_indicator {
index = "traces-*"
timestamp_field = "@timestamp"
filter = "service.name : \"bookshelf\""
good = "http.response.status_code < 500"
total = "http.response.status_code : *"
}
time_window {
duration = "30d"
type = "rolling"
}
objective {
target = 0.995
}
}
resource "elasticstack_kibana_alerting_rule" "slo_burn_rate" {
space_id = local.space_id
rule_id = "bookshelf-slo-burn-rate"
name = "Bookshelf availability burn rate"
consumer = "slo"
rule_type_id = "slo.rules.burnRate"
interval = "1m"
tags = ["bookshelf", "lab"]
params = jsonencode({
sloId = elasticstack_kibana_slo.availability.slo_id
windows = [
{ id = "w-1h", burnRateThreshold = 14.4, longWindow = { value = 1, unit = "h" }, shortWindow = { value = 5, unit = "m" }, actionGroup = "slo.burnRate.alert" },
{ id = "w-6h", burnRateThreshold = 6, longWindow = { value = 6, unit = "h" }, shortWindow = { value = 30, unit = "m" }, actionGroup = "slo.burnRate.high" },
{ id = "w-24h", burnRateThreshold = 3, longWindow = { value = 24, unit = "h" }, shortWindow = { value = 2, unit = "h" }, actionGroup = "slo.burnRate.medium" },
{ id = "w-72h", burnRateThreshold = 1, longWindow = { value = 72, unit = "h" }, shortWindow = { value = 6, unit = "h" }, actionGroup = "slo.burnRate.low" }
]
})
dynamic "actions" {
for_each = ["slo.burnRate.alert", "slo.burnRate.high", "recovered"]
content {
group = actions.value
id = elasticstack_kibana_action_connector.bookshelf_webhook.connector_id
params = jsonencode({ body = "{\"rule\":\"{{rule.name}}\",\"status\":\"{{alert.actionGroupName}}\"}" })
frequency {
summary = false
notify_when = "onActionGroupChange"
}
}
}
}
resource "elasticstack_kibana_maintenance_window" "deploy" {
space_id = local.space_id
title = "Bookshelf weekly deploy"
enabled = true
custom_schedule = {
start = "2026-11-15T22:00:00.000Z"
duration = "1h"
timezone = "UTC"
recurring = {
every = "1w"
on_week_day = ["SU"]
}
}
scope = {
alerting = {
kql = "kibana.alert.rule.tags : \"bookshelf\""
}
}
}
The rule resource also has alert_delay (a number of consecutive runs), flapping (look_back_window and status_change_threshold; the optional enabled needs Stack 9.3
or later, and the block needs 8.16 or later), artifacts (investigation_guide, from an inline content or a file content_path, and dashboards;
writing needs Stack 9.1 or later and importing them back needs 9.5.0 or later) and a rule_id (any format since Kibana 8.17). Two behaviors to remember:
removing flapping from the configuration does not clear the server-side value, and omitting artifacts does not clear stored ones. The provider also
has data sources such as elasticstack_kibana_alerting_rules to read execution status. Cases templates and the field library are covered on
Cases; dashboards in the section on
Dashboards as Code. State, plan review and CI are the same as for any other
Terraform root module (see Terraform); a rule’s api_key_owner is the Terraform user, so run the pipeline as the service user.
Reference (the Terraform Registry pages are rendered in the browser; the same documents are in the provider repository): kibana_alerting_rule, kibana_action_connector, kibana_maintenance_window, kibana_slo, provider configuration.
What can go wrong
-
400without a message about the body. Thekbn-xsrfheader is missing, or the actiongroupis not one of the rule type’s groups (checkGET /api/alerting/rule_types). -
401or403. Wrong credentials, or the identity lacksallon the rules and connectors features in the space, or the path has no/s/bookshelfprefix and the call went to the default space, where the connector does not exist (the rule is rejected for an unknown connector). -
409on create. The rule or connector id exists; usePUT(rule) orPUT /api/actions/connector/{id}, or delete and recreate. -
The update removed the actions.
PUTreplaces theactionsarray; send the full definition. -
The rule ran for a day and then stopped finding data. It runs with the last editor’s API key; a different identity saved it, or the service user lost privileges on the data. Check
api_key_ownerand use_update_api_key. -
Terraform wants to change the rule every run. JSON in
paramsis compared as text; writeparamswithjsonencodeconsistently and runterraform plantwice after the first apply to confirm there is no perpetual difference. -
Terraform cannot find the connector. The
connector_idmust be a UUID; the API idbookshelf-webhookis for scripts. -
Duplicates. A rule created by hand and the same rule in code both fire; import existing rules (
terraform import) or delete the hand-built ones. -
Imported or copied rules are disabled. Rules imported from an export arrive disabled and get a new API key when enabled.
Hands-on: apply the Bookshelf alerting set
-
Create the data views
bookshelf-tracesandbookshelf-logsif they do not exist, then run theapihelper definitions, create the connector and run its_executetest. The webhook receiver must log the manual message at/kibana. -
Create rules 1 to 5 with the commands of this page. For each,
GET /api/alerting/rule/<id>and checkenabledistrueandexecution_status.statusbecomesokafter a minute. -
Switch the load generator to failing-request mode and wait for the 5xx rule: the receiver logs one
Alertmessage, and the alert shows on the Alerts page. Restore normal traffic and watch the recovered message. -
Create the maintenance window, wait for its next occurrence or create one that starts now with a 15 minute duration, and trigger the 5xx rule again: the alert appears but no message reaches the receiver.
-
Snooze the rule with the
snooze_schedulecall and check on the rule details page that the snooze is shown. -
Delete everything with
DELETEcalls, then apply the Terraform configuration (terraform init,plan,apply) and compare the resulting rules with the ones you created by hand; runterraform planagain to confirm there are no changes.
In the books
None of the books covers the Kibana alerting API or the Elastic Terraform provider. Shah, Kibana 8 Quick Start Guide, chapter 6, creates rules and connectors only through the 8.x user interface, and the rule types, action frequency, maintenance window scopes, SLO and burn rate rules and artifacts on this page are all newer than the books. Publisher pages are listed in the bibliography of the section index.