Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install kibana-alerting-rules@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin kibana-alerting-rules v1.0.0 follows the Agent Plugins spec.
gh skills-hub install kibana-alerting-rules Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/kibana-alerting-rules/ Extract the ZIP to .github/skills/ in your repo. The folder name must match kibana-alerting-rules for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 34.6 KB
---
name: kibana-alerting-rules
description: >
Create and manage Kibana alerting rules and the action policies that notify on their
alerts, for both Universal Alerting and classic alerting. Use when the user wants
to be alerted or notified about conditions in their data, change where or how often
alerts notify (including snoozing notifications), edit, enable, disable, or delete
existing rules or action policies, or list existing alerting, including managing
rules with Terraform. Not for Security detection rules.
metadata:
author: elastic
version: 0.4.0
universal: true
compatibility: 'Classic rules: Kibana 8.x or 9.x and every Elastic Cloud Serverless
project. Universal Alerting: Kibana 9.6 or later, or Serverless Observability projects,
with the `alerting:v2:enabled` advanced setting on (default); action policies need
Kibana Workflows and an Enterprise or trial license. Self-managed, Elastic Cloud
Hosted, or Serverless. Requires the `elastic` CLI with `stack kb` support.'
---
# Kibana Alerting
Turn a monitoring goal into working alerting and manage what already exists. Create Universal Alerting rules and action
policies by default; use classic alerting only when the user names a classic rule type, edits an existing classic rule,
or Universal Alerting is unavailable. Load only the chosen system's references before writing anything.
<!-- begin-partial: preamble -->
## Environment Configuration
This skill executes Elasticsearch operations through the `elastic` CLI. If the
[`elastic` CLI](https://github.com/elastic/cli#configuration) is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.
This skill references operations in HTTP-shorthand form (e.g., `GET /`, `GET /_cat/indices`, `GET /{index}/_mapping`,
`GET /{index}/_settings/index.mode`, `POST /_query`). The [Operations](#operations) table at the end of this document
maps each shorthand to the equivalent `elastic` CLI command — always use the CLI rather than calling the HTTP API
directly.
<!-- end-partial: preamble -->
## Core concepts
Kibana has two alerting systems. They do not share rules, APIs, or notification wiring.
- **Universal Alerting** is the default for all new alerting, also called alerting v2. A rule evaluates an ES|QL query
on a schedule and opens alerts. Notifications are managed independently of rules through **action policies**. A
policy's matcher selects alerts by their content or scopes them to specific rules through routing tags, and the policy
dispatches the matched alerts to workflows (Slack, email, PagerDuty, and other connectors). A policy can be created
before, after, or together with the rules it matches. Available on Kibana 9.6 or later and in Serverless Observability
projects; Serverless Security and Elasticsearch projects do not offer it. Action policies and workflows require an
Enterprise or trial license; rules do not.
- **Classic alerting** covers the classic rule types listed in `classic-rule-types.md`. Its details live entirely in the
classic references — do not load them for any other task. Classic alerting has no action policies: each classic rule
notifies through its own actions, which run connectors.
## Universal Alerting availability
If the user states a Kibana version before 9.6, use classic alerting without the check below.
Otherwise, before the first Universal Alerting call, check it once with `GET kbn:/api/alerting/v2/rules` and
`per_page=1`:
| Response | Meaning | Do |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
| 200 | Available | Use Universal Alerting |
| 404, and `GET kbn:/api/status` succeeds | Not in this Kibana: a version before 9.6 (see `version.number`), or a Serverless Security or Elasticsearch project | Use classic alerting |
| 503 with code `ALERTING_DISABLED` | Turned off by an administrator (`alerting:v2:enabled`) | Use classic alerting |
| 403 | Available, but the user lacks the **Rules** feature privilege | Stop and tell the user which privilege they need; do not use classic alerting |
Any other result — another status code, a 404 followed by a failed `GET kbn:/api/status`, an authentication error, or no
connection — says nothing about availability: stop and report the error. Do not use classic alerting.
When using classic alerting, do not ask first, and say in the final report why the rule is classic: the stated version
or the meaning from the table. For a find or list request, report classic results only and say why. A request that needs
an action policy or routing tag has no classic equivalent; tell the user why Universal Alerting is unavailable instead.
## Process
1. **Identify the job.** Match the request to one or more rows below. A request can combine jobs — for example a new
rule and its notifications — and they can be done in either order, because a shared routing tag links a Universal
Alerting rule to its policies.
| Job | Example request | System | Read before writing |
| --------------------------------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Find or list | "Show me all production alerting rules" | Both systems, read-only — create, update, enable, or delete nothing | — |
| New rule with notifications | "Alert me / page on-call when CPU is above 90% on any host" | Universal Alerting | `universal-rules.md`, `universal-action-policies.md`, `universal-workflow-destinations.md` |
| New rule without notifications | "Record every time checkout latency exceeds 2 seconds" | Universal Alerting | `universal-rules.md` |
| Notifications only | "Send payments alerts to Slack instead of email", "Snooze the on-call policy" | Universal Alerting — action policies; a rule changes only to add a routing tag the user agrees to | `universal-action-policies.md`, plus `universal-workflow-destinations.md` when a destination changes |
| Edit an existing rule or change its lifecycle | "Disable rule `cpu-web`" | Either system, depends on where result appears | That system's references |
| New rule of a named classic type | "Create an Elasticsearch query rule that…" | Classic | `classic-rules.md`, `classic-rule-types.md`, plus `classic-actions-connectors-terraform.md` for notifications |
| Terraform for a rule | "Manage an index threshold rule with Terraform" | Route as any other request. The Terraform resource (`elasticstack_kibana_alerting_rule`) covers classic rules only: for Universal Alerting, tell the user and offer the API instead | `classic-actions-connectors-terraform.md` for a classic rule |
Reference paths are relative to `references/` (see [References](#references)). Never mix systems: Universal Alerting
rules have no rule-level actions, and classic rules have no action policies or routing tags.
2. **Find what the request refers to.** If the request does not identify which rules or action policies it intends — for
example "the payments rules" or "my production alerts" with no tag, name, or ID — ask the user before making any API
calls; do not search rule names to guess the set. When the user refers to an existing rule by ID, name, or tag,
search both systems — Universal Alerting first, then classic — and use whichever returns a match. Run both searches
even when the first one matches, so a rule with the same name or tag in the other system is not missed:
| Given | Universal Alerting | Classic alerting |
| ----------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| ID | `GET kbn:/api/alerting/v2/rules/{id}` | `GET kbn:/api/alerting/rule/{id}` |
| Name | `GET kbn:/api/alerting/v2/rules` with `search=<name>` | `GET kbn:/api/alerting/rules/_find` with `search=<name>&search_fields=name` |
| Tag | `GET kbn:/api/alerting/v2/rules` with `filter=metadata.tags:"<tag>"` | `GET kbn:/api/alerting/rules/_find` with `filter=alert.attributes.tags:"<tag>"` |
| Routing tag | `GET kbn:/api/alerting/v2/rules` with `filter=metadata.routing_tags:"<tag>"` | — (classic rules have no routing tags) |
List and find responses are paged: request the next `page` while the items returned so far are fewer than `total`.
Skip one search only when the user's wording belongs to a single system:
| User says | Search |
| ------------------------------------------------------------------------------------- | ----------------------- |
| "routing tag", "action policy", "alert kind" or "signal kind", "universal rule", "v2" | Universal Alerting only |
| A classic rule type ("index threshold rule", "Elasticsearch query rule") | Classic only |
| "connector", "tag", "label", or a bare name or ID | Both systems |
"Snooze" and "mute" do not determine which alerting system to use: classic rules are snoozed on the rule, while
Universal Alerting notifications are snoozed on action policies.
If only one system matches, use it. If both match, show both to the user and ask which they mean. If neither matches,
say so — do not create a rule in its place. For a find or list request with no system named, report the results from
both systems, labeled by system.
Before editing or deleting a rule, confirm matches with user to ensure they're mutating the intended object. Do not
assume without their confirmation unless a single result matches exactly.
Action policies exist only in Universal Alerting; find them with
[Find policies](references/universal-action-policies.md#find-policies).
3. **Verify by reading back.** After every write, read the rule or policy again and report its live id, name, enabled
state, and, for notifications, the matcher and destinations. Do not claim success without the read-back.
## Examples
### Notify on a new condition (Universal Alerting, default)
User: "Page the on-call workflow `wf-pagerduty` when CPU is above 90% on any host for 5 minutes."
1. Job: new rule with notifications → Universal Alerting. `GET kbn:/api/alerting/v2/rules` with `per_page=1` →
available.
2. Read `universal-rules.md`; `POST kbn:/api/alerting/v2/rules` with an alert-kind rule grouped by `host.name` and a
routing tag such as `notify-host-cpu-high`.
3. Read `universal-action-policies.md` and `universal-workflow-destinations.md`; check the license and `wf-pagerduty`,
then `POST kbn:/api/alerting/v2/action_policies` matching that routing tag.
4. Read both back and confirm.
### Route an existing rule's alerts somewhere new (Universal Alerting)
User: "Send alerts from rules tagged `team-payments` to Slack workflow `wf-slack` instead of email."
The user wants to change where alerts are sent, not what triggers them, so edit action policies and leave the rules'
queries unchanged. Alerts can match several policies, so changing one policy may leave another still sending email:
1. Find the rules: `GET kbn:/api/alerting/v2/rules` with `filter=metadata.tags:"team-payments"`, and collect their
`metadata.routing_tags`.
2. Read `universal-action-policies.md` and list the policies that send those rules' alerts: those that always match
(catch-alls, and tag matches without an expression) and, labeled as possible matches, those with a
`matcher.expression`.
3. Show them with their destinations and confirm with the user which ones to change. If the rules have no routing tags,
their alerts reach only catch-all and expression policies that other rules may share; ask whether to add a routing
tag to those rules and create a policy for it instead.
4. Verify `wf-slack`, then `PATCH` the `destinations` of each confirmed policy.
### Edit an existing rule of unknown system
User: "Snooze rule `cpu-web` for two hours."
1. `GET kbn:/api/alerting/v2/rules/cpu-web` → 404. `GET kbn:/api/alerting/rule/cpu-web` → found.
2. The rule is classic: read `classic-rules.md` and use its snooze call.
### Classic rule type named
User: "Create an Elasticsearch query rule that fires when more than 100 error logs arrive in 10 minutes."
The user named a classic rule type: read `classic-rules.md` and `classic-rule-types.md`, then create the classic rule
they describe.
## Guidelines
- Treat find and list requests as strictly read-only.
- Load classic references only for a named classic rule type, an existing classic rule, or when
[Universal Alerting is unavailable](#universal-alerting-availability); for every other job, use Universal Alerting
references only.
- Prefix paths with `kbn:/s/<space_id>/` for non-default Kibana spaces. Rules, policies, connectors, and workflows are
space-scoped and must share a space.
- Confirm with the user before deleting rules or action policies.
- Do **not** migrate classic rules to Universal Alerting; it is not supported. Edit a classic rule in place.
- Do **not** use this skill for Security detection rules: `consumer: "securitySolution"`/`"siem"` and
`/api/detection_engine/rules` belong to the Security Detections API.
## Common pitfalls
1. **Wrong system** — creating a classic rule for a new request that did not name a classic rule type while Universal
Alerting is available, or editing an existing rule without looking it up in both systems.
2. **Mixed concepts** — rule-level actions or connectors in a Universal Alerting answer, or action policies and routing
tags in a classic one.
3. **Wrong notification scope** — creating policies, workflows, or actions when the user only asked for a rule, or
skipping notifications when the user asked to be alerted, or inventing a destination the user did not name.
4. **Read-only violations** — creating or mutating anything when the user asked only to list or filter.
5. **Unverified success** — reporting success without reading the rule or policy back.
## References
- [universal-rules.md](references/universal-rules.md) — Universal rule kinds, fields, ES|QL query, recovery, no-data,
lifecycle
- [universal-action-policies.md](references/universal-action-policies.md) — Action policy find, create, update,
lifecycle, bulk, and ownership
- [universal-matching-grouping-throttle.md](references/universal-matching-grouping-throttle.md) — Matcher fields,
grouping modes, throttle strategies, dispatch flow
- [universal-workflow-destinations.md](references/universal-workflow-destinations.md) — Destination workflow
requirements, dispatch payload, example workflow
- [classic-rules.md](references/classic-rules.md) — Classic only (Process step 1): find, create, update, lifecycle,
tuning
- [classic-rule-types.md](references/classic-rule-types.md) — Classic only: rule types, params, consumers, action groups
- [classic-actions-connectors-terraform.md](references/classic-actions-connectors-terraform.md) — Classic only: rule
actions, workflows as connectors, Terraform
- [Kibana Alerting API](https://www.elastic.co/docs/api/doc/kibana/group/endpoint-alerting)
- [Kibana Universal Alerting API](https://www.elastic.co/docs/api/doc/kibana/group/endpoint-alerting-v2) — Request and
response fields, bounds, and error codes. Before writing a Universal Alerting request body, read the operation's page:
`https://www.elastic.co/docs/api/doc/kibana/operation/operation-<command>`, where `<command>` is the CLI command name
from the [Operations](#operations) table (for example `operation-patch-alerting-v2-action-policies-id`)
- [Alerting concepts](https://www.elastic.co/docs/explore-analyze/alerting/alerts)
- [Kibana Workflows](https://www.elastic.co/docs/explore-analyze/workflows)
## Operations
`elastic kb` is shorthand for `elastic stack kb`. Universal Alerting and Workflows write commands take the JSON body
from `--input-file '<path.json>'`. Add `--space '<space_id>'` for a non-default space. If the CLI rejects a command name
from this table, run `elastic kb alerting-v2 --help` (or the matching command group) and use the listed name.
| HTTP API (shorthand) | `elastic` CLI command |
| --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /_license` | `elastic es license get` |
| `GET kbn:/api/status` | `elastic kb system get-status` |
| `POST /_query` | `elastic es esql query --query '<esql>'` |
| `GET kbn:/api/alerting/v2/rules` | `elastic kb alerting-v2 get-alerting-v2-rules [--filter '<kql>'] [--search '<q>'] [--page <n>] [--per-page <n>] [--sort-field <field>] [--sort-order asc\|desc]` |
| `POST kbn:/api/alerting/v2/rules` | `elastic kb alerting-v2 post-alerting-v2-rules --input-file '<rule.json>'` |
| `GET kbn:/api/alerting/v2/rules/{id}` | `elastic kb alerting-v2 get-alerting-v2-rules-id --id '<id>'` |
| `PUT kbn:/api/alerting/v2/rules/{id}` | `elastic kb alerting-v2 put-alerting-v2-rules-id --id '<id>' --input-file '<rule.json>'` |
| `PATCH kbn:/api/alerting/v2/rules/{id}` | `elastic kb alerting-v2 patch-alerting-v2-rules-id --id '<id>' --input-file '<patch.json>'` |
| `DELETE kbn:/api/alerting/v2/rules/{id}` | `elastic kb alerting-v2 delete-alerting-v2-rules-id --id '<id>'` |
| `POST kbn:/api/alerting/v2/rules/{id}/_enable` | `elastic kb alerting-v2 post-alerting-v2-rules-id-enable --id '<id>'` |
| `POST kbn:/api/alerting/v2/rules/{id}/_disable` | `elastic kb alerting-v2 post-alerting-v2-rules-id-disable --id '<id>'` |
| `POST kbn:/api/alerting/v2/rules/_bulk_enable` | `elastic kb alerting-v2 post-alerting-v2-rules-bulk-enable --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/rules/_bulk_disable` | `elastic kb alerting-v2 post-alerting-v2-rules-bulk-disable --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/rules/_bulk_delete` | `elastic kb alerting-v2 post-alerting-v2-rules-bulk-delete --input-file '<ids.json>'` |
| `GET kbn:/api/alerting/v2/action_policies` | `elastic kb alerting-v2 get-alerting-v2-action-policies [--filter '<kql>'] [--search '<q>'] [--page <n>] [--per-page <n>] [--sort-field <field>] [--sort-order asc\|desc]` |
| `GET kbn:/api/alerting/v2/action_policies/{id}` | `elastic kb alerting-v2 get-alerting-v2-action-policies-id --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies` | `elastic kb alerting-v2 post-alerting-v2-action-policies --input-file '<policy.json>'` |
| `PUT kbn:/api/alerting/v2/action_policies/{id}` | `elastic kb alerting-v2 put-alerting-v2-action-policies-id --id '<id>' --input-file '<policy.json>'` |
| `PATCH kbn:/api/alerting/v2/action_policies/{id}` | `elastic kb alerting-v2 patch-alerting-v2-action-policies-id --id '<id>' --input-file '<patch.json>'` |
| `DELETE kbn:/api/alerting/v2/action_policies/{id}` | `elastic kb alerting-v2 delete-alerting-v2-action-policies-id --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies/{id}/_enable` | `elastic kb alerting-v2 post-alerting-v2-action-policies-id-enable --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies/{id}/_disable` | `elastic kb alerting-v2 post-alerting-v2-action-policies-id-disable --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies/{id}/_snooze` | `elastic kb alerting-v2 post-alerting-v2-action-policies-id-snooze --id '<id>' --input-file '<snooze.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/{id}/_unsnooze` | `elastic kb alerting-v2 post-alerting-v2-action-policies-id-unsnooze --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies/{id}/_update_api_key` | `elastic kb alerting-v2 post-alerting-v2-action-policies-id-update-api-key --id '<id>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_enable` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-enable --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_disable` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-disable --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_snooze` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-snooze --input-file '<ids-and-snooze.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_unsnooze` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-unsnooze --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_update_api_key` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-update-api-key --input-file '<ids.json>'` |
| `POST kbn:/api/alerting/v2/action_policies/_bulk_delete` | `elastic kb alerting-v2 post-alerting-v2-action-policies-bulk-delete --input-file '<ids.json>'` |
| `GET kbn:/api/workflows/connectors` | `elastic kb workflows get-workflows-connectors` |
| `GET kbn:/api/workflows/schema` | `elastic kb workflows get-workflows-schema --loose false` |
| `POST kbn:/api/workflows/test` | `elastic kb workflows post-workflows-test --input-file '<test.json>'` |
| `GET kbn:/api/workflows/executions/{executionId}` | `elastic kb workflows get-workflows-executions-executionid --execution-id '<id>'` |
| `GET kbn:/api/workflows/executions/{executionId}/logs` | `elastic kb workflows get-workflows-executions-executionid-logs --execution-id '<id>'` |
| `GET kbn:/api/workflows/workflow/{id}` | `elastic kb workflows get-workflows-workflow-id --id '<id>'` |
| `POST kbn:/api/workflows/workflow` | `elastic kb workflows post-workflows-workflow --input-file '<workflow.json>'` |
| `PUT kbn:/api/workflows/workflow/{id}` | `elastic kb workflows put-workflows-workflow-id --id '<id>' --input-file '<workflow.json>'` |
| `GET kbn:/api/actions/connector/{id}` | `elastic kb connectors get-actions-connector-id --id '<id>'` |
| `GET kbn:/api/alerting/rules/_find` | `elastic kb alerting get-alerting-rules-find [--filter '<kql>'] [--search '<q>'] [--per-page <n>] [--page <n>] [--sort-field <field>] [--sort-order asc\|desc]` |
| `POST kbn:/api/alerting/rule/{id}` | `elastic kb alerting post-alerting-rule-id --id '<id>' --name '<name>' --rule-type-id '<type>' --consumer '<consumer>' --schedule '<json>' --params '<json>' [--tags '<json>'] [--actions '<json>'] [--enabled]` |
| `GET kbn:/api/alerting/rule/{id}` | `elastic kb alerting get-alerting-rule-id --id '<id>'` |
| `PUT kbn:/api/alerting/rule/{id}` | `elastic kb alerting put-alerting-rule-id --id '<id>' --name '<name>' --schedule '<json>' --params '<json>' [--tags '<json>'] [--actions '<json>']` |
| `DELETE kbn:/api/alerting/rule/{id}` | `elastic kb alerting delete-alerting-rule-id --id '<id>'` |
| `POST kbn:/api/alerting/rule/{id}/_enable` | `elastic kb alerting post-alerting-rule-id-enable --id '<id>'` |
| `POST kbn:/api/alerting/rule/{id}/_disable` | `elastic kb alerting post-alerting-rule-id-disable --id '<id>' [--untrack]` |
| `POST kbn:/api/alerting/rule/{id}/_mute_all` | `elastic kb alerting post-alerting-rule-id-mute-all --id '<id>'` |
| `POST kbn:/api/alerting/rule/{id}/_unmute_all` | `elastic kb alerting post-alerting-rule-id-unmute-all --id '<id>'` |
| `POST kbn:/api/alerting/rule/{id}/_update_api_key` | `elastic kb alerting post-alerting-rule-id-update-api-key --id '<id>'` |
| `POST kbn:/api/alerting/rule/{rule_id}/alert/{alert_id}/_mute` | `elastic kb alerting post-alerting-rule-rule-id-alert-alert-id-mute --rule-id '<rule_id>' --alert-id '<alert_id>'` |
| `POST kbn:/api/alerting/rule/{rule_id}/alert/{alert_id}/_unmute` | `elastic kb alerting post-alerting-rule-rule-id-alert-alert-id-unmute --rule-id '<rule_id>' --alert-id '<alert_id>'` |
| `POST kbn:/api/alerting/rule/{id}/snooze_schedule` | `elastic kb alerting post-alerting-rule-id-snooze-schedule --id '<id>' --schedule '<json>'` |
| `DELETE kbn:/api/alerting/rule/{ruleId}/snooze_schedule/{scheduleId}` | `elastic kb alerting delete-alerting-rule-ruleid-snooze-schedule-scheduleid --rule-id '<ruleId>' --schedule-id '<scheduleId>'` |
classic-actions-connectors-terraform.md 3.2 KB
# Connectors, Actions, Terraform, and Workflows
## Actions in rules
Each action references a connector by ID, an action **group**, action **params** (Mustache templates), and a per-action
**frequency** object.
Each connector type has its own minimum license — for example, Slack, email, and PagerDuty connectors require Gold.
| Field | Purpose |
| ----------------------- | ----------------------------------------------------------------- |
| `id` | Connector ID (Slack, PagerDuty, Index, workflow, etc.) |
| `group` | Trigger state (e.g., `"threshold met"`, `"Recovered"`) |
| `params` | Connector-specific payload with Mustache variables |
| `frequency.summary` | `true` for digest of all alerts; `false` for per-alert |
| `frequency.notify_when` | `onActionGroupChange`, `onActiveAlert`, or `onThrottleInterval` |
| `frequency.throttle` | Minimum repeat interval (e.g., `"10m"`) with `onThrottleInterval` |
Mustache variables include `{{rule.name}}`, `{{context.*}}`, `{{alerts.new.count}}`, `{{rule.url}}`. For full connector
payloads and Mustache lambdas (`EvalMath`, `FormatDate`, `ParseHjson`), see the
[Kibana connectors API](https://www.elastic.co/docs/api/doc/kibana/group/endpoint-actions).
**Best practice:** Always pair an active action with a **Recovered** action for PagerDuty, Jira, and ServiceNow so
incidents auto-close.
## Triggering Kibana Workflows from rules
> Preview feature — Elastic Stack 9.3+ and Elastic Cloud Serverless. APIs may change.
Attach a workflow as a rule action using the workflow ID as the connector ID. Set `params: {}` — alert context flows
through the `event` object inside the workflow. In the UI: **Stack Management → Rules → Actions → Workflows**. Only
`enabled: true` workflows appear in the picker.
Update the rule with `PUT kbn:/api/alerting/rule/{id}` and an `actions` array referencing the workflow connector.
## Terraform (rules-as-code)
Use the `elasticstack` provider resource `elasticstack_kibana_alerting_rule`.
```hcl
resource "elasticstack_kibana_alerting_rule" "cpu_alert" {
name = "CPU usage critical"
consumer = "stackAlerts"
rule_type_id = ".index-threshold"
interval = "1m"
enabled = true
params = jsonencode({
index = ["metrics-*"]
timeField = "@timestamp"
aggType = "avg"
aggField = "system.cpu.total.pct"
groupBy = "top"
termField = "host.name"
termSize = 10
threshold = [0.9]
thresholdComparator = ">"
timeWindowSize = 5
timeWindowUnit = "m"
})
tags = ["infrastructure", "production"]
}
```
Notes:
- `params` must be JSON-encoded via `jsonencode()`.
- Reference connector IDs via `elasticstack_kibana_action_connector` data source or resource.
- Import: `terraform import elasticstack_kibana_alerting_rule.my_rule <space_id>/<rule_id>` (`default` for the default
space).
See
[Terraform: elasticstack_kibana_alerting_rule](https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_alerting_rule).
classic-rule-types.md 6.4 KB
# Rule Types and Parameters
Use this reference when choosing `rule_type_id`, `consumer`, and `params` for a new rule.
## Common metric and threshold rule types
| Rule type | `rule_type_id` | Typical `consumer` | Use when |
| ------------------------------ | ------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Index threshold | `.index-threshold` | `stackAlerts` | Aggregate a numeric field over a time window, compare to a threshold, optionally group by a term field (per-host/per-service alerts) |
| Elasticsearch query | `.es-query` | `stackAlerts` | Count or aggregate via Query DSL / ES\|QL embedded in params |
| Observability metric threshold | `metrics.alert.threshold` | `metrics` or `infrastructure` | Observability UI metric rules on infrastructure/metrics data |
For **"metric exceeds X for Y minutes, grouped by host"**, prefer `.index-threshold` with `stackAlerts` unless the
deployment exposes only the Observability metric threshold type.
## Index threshold params (`.index-threshold`)
| Param | Purpose |
| ----------------------------------- | ------------------------------------------------------------------------------------------------- |
| `index` | Array of index patterns to query |
| `timeField` | Time field (usually `@timestamp`) |
| `aggType` | Aggregation: `avg`, `max`, `min`, `sum`, `count` |
| `aggField` | Numeric field to aggregate (omit for `count`) |
| `groupBy` | `all` (single series) or `top` (per-term series) |
| `termField` | Field to group by when `groupBy` is `top` (e.g., `host.name`) |
| `termSize` | Max terms when grouping (use a generous value for "any host") |
| `threshold` | Array of threshold values (match field scale: `0.9` for fractional CPU pct, `90` for 0–100 scale) |
| `thresholdComparator` | `>`, `>=`, `<`, `<=`, `between`, etc. |
| `timeWindowSize` / `timeWindowUnit` | Lookback window (`5` + `m` = five minutes) |
**Example — CPU > 90% on any host for 5 minutes:**
```json
{
"index": ["eval-alert-metrics"],
"timeField": "@timestamp",
"aggType": "avg",
"aggField": "system.cpu.total.pct",
"groupBy": "top",
"termField": "host.name",
"termSize": 1000,
"threshold": [0.9],
"thresholdComparator": ">",
"timeWindowSize": 5,
"timeWindowUnit": "m"
}
```
Pair with `"schedule": { "interval": "5m" }` so the check interval aligns with the lookback window.
## Elasticsearch query params (`.es-query`)
| Param | Purpose |
| ----------------------------------- | ---------------------------------- |
| `index` | Index patterns |
| `timeField` | Time field |
| `esQuery` | JSON string of Query DSL query |
| `threshold` / `thresholdComparator` | Hit count or aggregation threshold |
| `timeWindowSize` / `timeWindowUnit` | Lookback window |
| `size` | Documents to evaluate |
## Valid `consumer` values
`alerts`, `apm`, `discover`, `infrastructure`, `logs`, `metrics`, `ml`, `monitoring`, `securitySolution`, `siem`,
`stackAlerts`, `uptime`
Using the wrong consumer for a rule type returns **400**. Match the consumer to the rule type's owning application
(Stack rules → `stackAlerts`; Observability metrics → `metrics` or `infrastructure`).
## Action groups
Each rule type defines action **groups** (trigger states). Common Stack threshold groups:
- `.index-threshold` — `"threshold met"`, `"Recovered"`
- `.es-query` — `"query matched"`, `"Recovered"`
Discover valid groups for a rule type in Kibana **Stack Management → Rules → Rule types**, or in the rule-type metadata
returned by the Kibana Alerting API (not yet exposed as an `elastic kb alerting` subcommand).
## Required and optional rule body fields
| Field | Required | Notes |
| -------------------------- | ---------- | ------------------------------------------------------------- |
| `name` | yes | Display name |
| `rule_type_id` | yes | Immutable after create |
| `consumer` | yes | Immutable after create |
| `schedule` | yes | e.g., `{"interval": "5m"}` — minimum typically `1m` |
| `params` | yes | Rule-type-specific |
| `enabled` | no | Default `true` |
| `tags` | no | For filtering via find API |
| `actions` | no | Omit when the user only asks to create the rule condition |
| `alert_delay` | no | e.g., `{"active": 3}` — fire only after N consecutive matches |
| `flapping` | no | Override flapping detection |
| `notify_when` / `throttle` | deprecated | Set `frequency` per action instead |
classic-rules.md 8.3 KB
# Classic Alerting Rules
Use this reference for classic Kibana alerting rules (`kbn:/api/alerting/rule`). A classic rule has three parts:
**conditions** (`params` + `rule_type_id`), a **schedule** (how often conditions are checked), and optional **actions**
(connectors run when alerts fire).
Use classic rules only when the user names a classic rule type or edits an existing classic rule. Classic rules cannot
be migrated to Universal Alerting; edit them in place.
Operations in this reference are written in HTTP shorthand (`kbn:/...`). Run each with the `elastic` CLI command that
the [Operations](../SKILL.md#operations) table maps it to; the CLI handles authentication and headers.
## Requirements
- **Privileges** — `all` on the owning Kibana feature (Stack Rules, Observability, Security, etc.) and `all` on Rules
Settings. Managing connectors needs `all` on Actions and Connectors; `read` is sufficient to attach existing
connectors as rule actions.
- **On-premises encryption key** — configure a stable `xpack.encryptedSavedObjects.encryptionKey` in `kibana.yml` before
creating rules. It encrypts rule API keys and connector secrets. If it is unset, each restart regenerates it and
breaks existing rules; all Kibana nodes in a cluster must share the same key.
- **Availability** — Kibana 8.x or 9.x, and every Elastic Cloud Serverless project.
## Find and list rules
Call `GET kbn:/api/alerting/rules/_find` with query parameters that narrow results instead of dumping every rule:
- **By tag:** `filter=alert.attributes.tags:"production"` (KQL on saved-object attributes).
- **By text:** `search` with `search_fields` and `default_search_operator` as needed.
- **Paging:** set `per_page` and iterate `page` when results may exceed one page.
- **Sort:** `sort_field=name` and `sort_order=asc` for stable listings.
Enumerate matching rule ids and names. Query alerting rules specifically, not connectors or streams.
## Create a rule
1. **Choose the rule type before writing params.** Match the user's intent to a metric or threshold rule type, not a
log, anomaly, or unrelated type:
- **Numeric metric over a time window, optionally per host or service** → `.index-threshold` with
`consumer: "stackAlerts"`.
- **Document count or Query DSL condition** → `.es-query` with `consumer: "stackAlerts"`.
- **Observability metric in the metrics app** → `metrics.alert.threshold` with `consumer: "metrics"` or
`"infrastructure"`.
Read [classic-rule-types.md](classic-rule-types.md) for param schemas, valid consumers, and action groups. When the
user specifies an index, field, threshold, duration, and grouping field, encode all of them explicitly in `params` —
do not substitute a connector or action for the condition.
2. **Encode threshold, duration, and grouping correctly.** These three dimensions are independent:
- **Threshold:** set `threshold` and `thresholdComparator` on the aggregated value. Match field scale — ECS
`system.cpu.total.pct` is typically fractional (`0.9` for 90%); use `90` only when the field is on a 0–100 scale.
- **"For N minutes" semantics:** set `timeWindowSize` and `timeWindowUnit` in `params` (lookback evaluated each run).
Align `schedule.interval` with that window (for example, both five minutes) so a brief spike does not fire on a
mismatched cadence. Add `alert_delay: {"active": N}` only when the user wants N **consecutive** matching runs, not
a single lookback window.
- **Per-host or per-entity grouping:** for `.index-threshold`, set `groupBy: "top"`, `termField` to the grouping
field (for example, `host.name`), and a `termSize` large enough to cover all entities ("any host"). Without
grouping, the rule aggregates globally and does not alert per host.
3. **Build the create payload.** Required fields: `name`, `rule_type_id`, `consumer`, `schedule`, `params`. Optional:
`tags`, `enabled`, `actions`, `alert_delay`, `flapping`. Use the user-supplied rule id in the URL when given;
otherwise let Kibana generate one.
**Example — CPU > 90% on any host for 5 minutes on `eval-alert-metrics`:**
```json
{
"name": "CPU exceeds 90% for 5 minutes",
"rule_type_id": ".index-threshold",
"consumer": "stackAlerts",
"schedule": { "interval": "5m" },
"params": {
"index": ["eval-alert-metrics"],
"timeField": "@timestamp",
"aggType": "avg",
"aggField": "system.cpu.total.pct",
"groupBy": "top",
"termField": "host.name",
"termSize": 1000,
"threshold": [0.9],
"thresholdComparator": ">",
"timeWindowSize": 5,
"timeWindowUnit": "m"
},
"tags": ["production"]
}
```
Omit `actions` when the user only asks to create the rule condition.
4. **Create and confirm.** Call `POST kbn:/api/alerting/rule/{id}` with the payload. On **409 Conflict**, the id already
exists — call `GET kbn:/api/alerting/rule/{id}` to inspect it or choose a different id. After a successful create,
call `GET kbn:/api/alerting/rule/{id}` and confirm the live rule id, name, and enabled state.
## Notify through connectors
Classic rules notify through inline `actions`, each referencing a connector, an action group, Mustache `params`, and a
per-action `frequency`. Attach actions only when the user asks for notifications, and use the connector or destination
the user names. When the user asks to be notified but names no destination, create the rule, then ask where
notifications should go before adding actions; never invent a connector. Read
[classic-actions-connectors-terraform.md](classic-actions-connectors-terraform.md) for the action object, Mustache
variables, workflow connectors, and Terraform.
- Set `frequency` inside each action object — rule-level `notify_when` and `throttle` are deprecated.
- A rule action cannot reference a connector from a different space — the rule and its connectors must share one space.
- Pair active notification actions with a **Recovered** action for PagerDuty, Jira, and ServiceNow so incidents close.
- Debug action templates with `{{{.}}}` in any template field — it renders the whole variable context as JSON, which
helps discover correct paths like `{{context.reason}}` or `{{alert.flapping}}`.
## Update a rule
Read, then replace. Call `GET kbn:/api/alerting/rule/{id}`, merge the intended changes, then
`PUT kbn:/api/alerting/rule/{id}` with the **complete** rule body. On **409 Conflict**, another user changed the rule —
re-fetch and retry. `rule_type_id` and `consumer` are immutable; delete and recreate the rule to change them.
## Change lifecycle
Call the narrowest endpoint:
- **Disable / enable** — `POST kbn:/api/alerting/rule/{id}/_disable` (the rule keeps its config);
`POST kbn:/api/alerting/rule/{id}/_enable`.
- **Mute all alerts** — `POST kbn:/api/alerting/rule/{id}/_mute_all`; restore with
`POST kbn:/api/alerting/rule/{id}/_unmute_all`.
- **Mute one alert** — `POST kbn:/api/alerting/rule/{rule_id}/alert/{alert_id}/_mute`; unmute with
`POST kbn:/api/alerting/rule/{rule_id}/alert/{alert_id}/_unmute`.
- **Snooze** — `POST kbn:/api/alerting/rule/{id}/snooze_schedule`; remove with
`DELETE kbn:/api/alerting/rule/{ruleId}/snooze_schedule/{scheduleId}`.
- **Delete** — `DELETE kbn:/api/alerting/rule/{id}`.
- **API key ownership failure** — `POST kbn:/api/alerting/rule/{id}/_update_api_key`.
For planned downtime spanning multiple rules, prefer a maintenance window over disabling or snoozing each rule.
## Tuning
- `alert_delay: {"active": N}` requires N consecutive matching runs before an alert fires.
- The `flapping` object suppresses unstable alerts per rule (GA in 9.3; earlier versions support only space-level
flapping settings).
- The minimum recommended check interval is `1m`; expensive rules are cancelled after the server run timeout (default
`5m`).
## Common failure modes
1. **Wrong rule type** — using a log or ML rule for a metric threshold condition.
2. **Missing per-entity grouping** — global aggregation when the user asked for "any host" or "per service".
3. **Threshold scale mismatch** — `90` vs `0.9` on fractional CPU fields.
4. **Duration conflated with schedule** — a one-minute schedule with a five-minute window behaves differently from both
set to five minutes.
5. **Concurrent update conflicts** — PUT without a fresh GET returns 409.
6. **Import/export** — saved-object import disables rules and strips connector secrets.
universal-action-policies.md 20.4 KB
# Universal Alerting Action Policies
Action policies route Universal Alerting alerts to notifications. A rule never names its destinations; policies match
its alerts and dispatch them to workflows.
Operations in this reference are written in HTTP shorthand (`kbn:/...`). Run each with the `elastic` CLI command that
the [Operations](../SKILL.md#operations) table maps it to; the CLI handles authentication and headers.
## Contents
- [How action policies work](#how-action-policies-work)
- [Requirements](#requirements)
- [Find policies](#find-policies)
- [Matcher usage](#matcher-usage)
- [Link rules and policies with routing tags](#link-rules-and-policies-with-routing-tags)
- [Grouping and throttle](#grouping-and-throttle)
- [Create or upsert a policy](#create-or-upsert-a-policy)
- [Update a policy](#update-a-policy)
- [Lifecycle](#lifecycle)
- [Bulk changes](#bulk-changes)
- [Ownership and portability](#ownership-and-portability)
- [Common failure modes](#common-failure-modes)
## How action policies work
An **action policy** is a space-scoped saved object. One policy can match alerts from many rules, and one rule's alerts
can match many policies.
- **Matcher** — selects alerts. `matcher.tags` matches a rule's `metadata.routing_tags` (any-of, exact, case-sensitive).
`matcher.expression` is KQL evaluated against each alert. When both are set, an alert must satisfy both. A policy
without a matcher is a **catch-all** that matches every alert in the space.
- **Grouping** — how many notifications matched alerts produce: `per_alert` (one per alert, default), `all` (one
notification that contains every matching alert), or `per_field` (one per distinct value of up to 16 alert fields).
- **Throttle** — how often a group notifies: `on_status_change`, `per_status_interval`, `time_interval`, or
`every_time`. The allowed strategies depend on the grouping mode.
- **Destinations** — one to ten workflows, each `{ "type": "workflow", "id": "<workflow_id>" }`. See
[universal-workflow-destinations.md](universal-workflow-destinations.md).
**Dispatch.** Rules with `kind: alert` produce alerts with a status of `pending`, `active`, `recovering`, or `inactive`.
A dispatcher in each space evaluates every enabled, non-snoozed policy against those alerts, groups and throttles the
matches, and schedules each destination workflow with the grouped alerts as `inputs.payload`. Delivery is at-least-once.
Rules with `kind: signal` produce no alerts and never notify. Field-level detail is in
[universal-matching-grouping-throttle.md](universal-matching-grouping-throttle.md).
## Requirements
- **License** — notifications need an active Enterprise (or trial) license: action policies and Kibana Workflows, which
every policy dispatches to, both require it. Rules run and open alerts on any license.
- Creating, upserting, updating, and enabling a policy is license-gated; a write without a qualifying license fails
with 403 `ACTION_POLICY_LICENSE_NOT_SUPPORTED`. Reading, disabling, snoozing, deleting, and rotating the API key
work on any license.
- The license is checked again at dispatch time. If it lapses, matched alerts are recorded as dispatch failures and no
workflow is scheduled.
- Check with `GET /_license`: continue only when `license.type` is `enterprise` or `trial` and `license.status` is
`active`.
- **Privileges** — the **Action Policies** feature (`alerting_v2_action_policies`): `read` to list and get, `all` to
write. Create, upsert, and update also require `read` on the **Rules** feature (`alerting_v2_rules`). Verifying a
destination requires the **Workflows** feature (`workflowsManagement`) **Read** sub-privilege.
- **Workflows** — Kibana Workflows must be available, because every destination is a workflow.
- **Spaces** — policies are space-scoped and only match alerts and dispatch workflows in their own space. Prefix paths
with `kbn:/s/<space_id>/` for a non-default space.
## Find policies
Call `GET kbn:/api/alerting/v2/action_policies`:
- **Filter** with KQL on `id`, `name`, `description`, or `enabled` (for example `filter=enabled: true`).
- **Search** free text in `name` and `description` with `search`.
- **Page** with `page` and `per_page` (max 100; `page × per_page` must not exceed 10,000).
- **Sort** with `sort_field` (`name`, `created_at`, `updated_at`) and `sort_order`.
Read one policy with `GET kbn:/api/alerting/v2/action_policies/{id}`. Report ids, names, enabled state, matcher, and
destinations. Policies cannot be searched or filtered by matcher or destination, so finding them by those fields means
reading every page; do that only when the user asks to find policies by those criteria or to reuse an existing policy
that meets them. Creating a policy does not require searching first.
**Policies that send a rule's alerts.** An alert can match several policies, so changing where a rule's alerts go means
finding all of them, not just one. Page through every policy and sort them into two lists:
- **Always match** — catch-all policies (no `matcher`), and policies whose `matcher.tags` share a value with the rule's
`metadata.routing_tags` and that have no `matcher.expression`.
- **May match** — policies with a `matcher.expression` and either no `matcher.tags` or `matcher.tags` that share a value
with the rule's `metadata.routing_tags`. The expression is evaluated against each alert's content at dispatch time, so
whether it matches the rule's alerts cannot be decided in advance. Do not try to evaluate it.
Skip policies whose `matcher.tags` share no value with the rule's routing tags; they never match its alerts.
Show both lists with each policy's destinations, and each possible match with its expression, and confirm with the user
which ones to change before writing.
## Matcher usage
| User request | Matcher |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A routing tag ("rules with routing tag team-payments") | `"matcher": { "tags": ["team-payments"] }`. `matcher.tags` matches values in a rule's `metadata.routing_tags`. If no rule carries the tag yet, the policy still applies to rules that get it later; tell the user. |
| A plain tag ("rules tagged team-payments") | Find the rules first with `GET kbn:/api/alerting/v2/rules` and `filter=metadata.tags:"team-payments"`, then match their `metadata.routing_tags`. If they have no routing tags, ask whether to add one to those rules before creating the policy. |
| Specific rules (names or ids) | Read each with `GET kbn:/api/alerting/v2/rules/{id}`. Reuse a routing tag that only those rules carry; otherwise choose a new routing tag that names the notification's purpose and add it to each rule's `metadata.routing_tags` and the policy's `matcher.tags`. Confirm no other rule carries the tag with `filter=metadata.routing_tags:"<tag>"`. |
| Alert content | `matcher.expression`, for example `severity: "critical"`; combine with `tags` to scope it to a set of rules. |
| A group without a tag or rule names ("the payments rules") | Ask for the routing tag or the specific rules before writing anything. Do not search rule names to guess the set. |
| No scope | Ask. Omit `matcher` (every alert in the space) only after the user confirms a catch-all. |
A rule without routing tags only matches catch-all and expression-only policies. Routing tags are replaced whole on a
rule PATCH (`PATCH kbn:/api/alerting/v2/rules/{id}`), so re-send the existing ones:
```json
{ "metadata": { "routing_tags": ["production", "notify-high-cpu-prod"] } }
```
Write `matcher.expression` against the documented alert fields only (`alert_id`, `alert_status`, `group_hash`,
`last_event_timestamp`, `severity`, `data.*`). Rule fields are not available — scope by rule with `matcher.tags`. An
expression that fails to evaluate matches nothing, so quote string values.
## Link rules and policies with routing tags
A rule and a policy are linked only by a shared string: a value in the rule's `metadata.routing_tags` that also appears
in the policy's `matcher.tags`. Neither object stores the other's id, and matching happens when alerts are dispatched,
so the rule and the policy can be written in either order; the link applies to alerts dispatched once both exist.
Kibana's rule authoring UI uses the same mechanism — it previews the policies a rule's routing tags match and lets the
user create a policy while composing the rule. Signal rules cannot carry routing tags.
1. **New rule, existing policy.** When the user names a policy ("send it through the on-call policy"), read it with
`GET kbn:/api/alerting/v2/action_policies/{id}` and put one of its `matcher.tags` in the new rule's
`metadata.routing_tags`. Check its `matcher.expression` as well — an expression can still exclude the rule's alerts.
A policy without `matcher.tags` (catch-all or expression-only) needs no routing tag on the rule. When the user
describes a policy without naming it, find it with [Find policies](#find-policies) or ask; policies cannot be
filtered by matcher, so finding one by tag means reading every page.
2. **New rule, policy later.** When the user wants the rule now and notifications later, or names a team routing tag
(`team-payments`), set that tag in `metadata.routing_tags` when creating the rule. Its alerts match no policy until
one with the same value in `matcher.tags` exists; tell the user. Creating that policy later needs no rule update.
3. **Rule and policy together.** When one request asks for the rule and its notification, choose the tag once — a new
tag named for the notification's purpose, or the user's team tag — create the rule with it in
`metadata.routing_tags`, prepare the destination workflow, then create the policy with the same value in
`matcher.tags`. Read both back and confirm the rule's `metadata.routing_tags` and the policy's `matcher.tags` share
the value.
## Grouping and throttle
The pair must be compatible:
| Grouping | Valid throttle strategies | When `throttle` is omitted |
| ------------------- | ------------------------------------------------------- | -------------------------- |
| `per_alert` | `on_status_change`, `per_status_interval`, `every_time` | `on_status_change` |
| `all` / `per_field` | `time_interval`, `every_time` | Unthrottled |
- `per_status_interval` and `time_interval` require `interval` (for example `"15m"`, max `"365d"`); the other strategies
reject it.
- For `all` and `per_field`, always send `throttle`: without it the dispatcher notifies on every new alert event, like
`every_time`.
- `per_field` fields are paths on the alert: rule query columns live under `data.` (for example `data.service.name`),
and a path that does not resolve groups as `null`.
- Use `per_alert` + `on_status_change` for paging and incident tools, `per_field` or `all` with `time_interval` for
digests, and `every_time` only when the user accepts one notification per evaluation.
## Create or upsert a policy
Send notifications to the destination the user names (a workflow, channel, or person). When the user asks to be notified
but names no destination, create the rule, then ask where notifications should go before creating the policy; never
invent a destination.
**Before every create, upsert, or update**, run the destination checks in
[universal-workflow-destinations.md](universal-workflow-destinations.md#use-an-existing-workflow) for every destination
the policy will have. Each of these writes makes the caller the policy's API key owner, so dispatched workflows run with
that user's privileges from then on. The license requirement is in [Requirements](#requirements).
Required fields: `name` and `destinations`. Optional: `description`, `matcher`, `grouping`, `throttle`. Read the
operation's
[API reference page](https://www.elastic.co/docs/api/doc/kibana/operation/operation-post-alerting-v2-action-policies)
for every field and bound.
- `POST kbn:/api/alerting/v2/action_policies` → server-generated id, 201.
- `PUT kbn:/api/alerting/v2/action_policies/{id}` → client-supplied id (`[a-zA-Z0-9_-]`, max 150 characters); 201 when
created, 200 when it replaces an existing policy.
New policies start enabled and unsnoozed. Create, upsert, and update bodies accept only configuration fields; a body
containing `enabled` or `snoozed_until` returns 400. To start a policy paused, create it and then call `_disable` or
`_snooze`. After the write, call `GET kbn:/api/alerting/v2/action_policies/{id}` and report the live id, name, enabled
state, and matcher.
Name shared policies by intent ("Page on critical", "Notify production alerts") and single-rule policies after the rule
(`Notify on <rule-name>`).
**One rule to an on-call workflow:**
```json
{
"name": "Notify on high-cpu-prod",
"description": "Default notification for high-cpu-prod",
"destinations": [{ "type": "workflow", "id": "wf-oncall-email" }],
"matcher": { "tags": ["notify-high-cpu-prod"] },
"grouping": { "mode": "per_alert" },
"throttle": { "strategy": "on_status_change" }
}
```
**Page on critical alerts from production rules:**
```json
{
"name": "Page on critical production alerts",
"destinations": [{ "type": "workflow", "id": "wf-pagerduty" }],
"matcher": { "tags": ["production"], "expression": "severity: \"critical\"" },
"grouping": { "mode": "per_alert" },
"throttle": { "strategy": "on_status_change" }
}
```
**Hourly digest per service:**
```json
{
"name": "Hourly payments digest",
"destinations": [{ "type": "workflow", "id": "wf-slack-digest" }],
"matcher": { "tags": ["team-payments"] },
"grouping": { "mode": "per_field", "fields": ["data.service.name"] },
"throttle": { "strategy": "time_interval", "interval": "1h" }
}
```
## Update a policy
**Before every create, upsert, or update**, run the destination checks in
[universal-workflow-destinations.md](universal-workflow-destinations.md#use-an-existing-workflow) for every destination
the policy has after the update. Each of these writes makes the caller the policy's API key owner, so dispatched
workflows run with that user's privileges from then on. The license requirement is in [Requirements](#requirements).
Prefer `PATCH kbn:/api/alerting/v2/action_policies/{id}` for partial changes:
- Omitted fields are unchanged; `null` clears `description`, `matcher`, `grouping`, or `throttle`.
- `matcher` leaves merge independently: `{ "matcher": { "expression": null } }` removes the KQL and keeps the tags.
- `destinations`, `grouping`, and `throttle` are replaced whole — re-send `interval` when changing a throttle.
- The merged result is re-validated, so an incompatible grouping and throttle pair returns 400.
Use `PUT` only to replace the full configuration; fields left out of a PUT body are removed. Both PATCH and PUT keep the
policy's enabled and snooze state. On **409** `ACTION_POLICY_VERSION_CONFLICT`, another caller changed the policy —
re-read it with `GET` and retry. The id is permanent; to change it, create a new policy and delete the old one.
## Lifecycle
- **Snooze** — a pause with a known end. `POST kbn:/api/alerting/v2/action_policies/{id}/_snooze` with
`{ "snoozed_until": "<ISO-8601>" }`. The timestamp must be in the future; convert durations ("for 2 hours") to an
absolute UTC time. Snooze works on enabled and disabled policies and leaves `enabled` unchanged. Snoozing again
replaces the end time; dispatch resumes on its own once it passes. End it early with
`POST kbn:/api/alerting/v2/action_policies/{id}/_unsnooze`.
- **Disable** — an open-ended stop. `POST kbn:/api/alerting/v2/action_policies/{id}/_disable`; resume with
`POST kbn:/api/alerting/v2/action_policies/{id}/_enable` (license-gated).
- **Rotate the API key** — `POST kbn:/api/alerting/v2/action_policies/{id}/_update_api_key` binds the policy to the
caller's credentials. Use it when the original owner lost privileges or left.
After rotation, every dispatch runs with the caller's privileges. Rotation itself does not check that the caller can
run the destinations. Before rotating:
1. Read the policy's `destinations`.
2. For each workflow, `GET kbn:/api/workflows/workflow/{id}` and confirm `permissions.execute` is `true` for the
caller.
3. For each `connector-id` in the workflow's steps, confirm `GET kbn:/api/actions/connector/{id}` resolves for the
caller.
Rotation does not change the workflow's structure, so do not re-check it.
- **Delete** — `DELETE kbn:/api/alerting/v2/action_policies/{id}` (204). Confirm with the user first.
## Bulk changes
Resolve ids with [Find policies](#find-policies) first, then send `{ "ids": [...] }` (1–100 unique ids) to the matching
endpoint:
- `POST kbn:/api/alerting/v2/action_policies/_bulk_enable` (license-gated)
- `POST kbn:/api/alerting/v2/action_policies/_bulk_disable`
- `POST kbn:/api/alerting/v2/action_policies/_bulk_snooze` (also takes `snoozed_until`)
- `POST kbn:/api/alerting/v2/action_policies/_bulk_unsnooze`
- `POST kbn:/api/alerting/v2/action_policies/_bulk_update_api_key`
- `POST kbn:/api/alerting/v2/action_policies/_bulk_delete` (confirm with the user first)
The response is 200 even when some ids fail — read `affected_count` and every entry in `errors` (`id`, `error.code`,
`error.message`) and report each failure.
## Ownership and portability
- Every create, upsert, update, and key rotation binds the policy to the caller's credentials, and dispatched workflows
run with those privileges. Re-check the destination requirements before each of these writes, even when `destinations`
does not change.
- Anyone who can edit a destination workflow can run steps with the owner's privileges, so manage policies with a user
whose privileges match what the destination workflows need.
- Authenticate as a user or with an Elasticsearch API key; Elastic Cloud (UIAM) API keys are rejected with 400
`ACTION_POLICY_CLOUD_API_KEY_NOT_SUPPORTED`.
- The stored API key is encrypted, and policies are not part of saved-object import or export. Recreate them with `PUT`
(stable ids) in each space or cluster.
- The `elasticstack` Terraform provider has no action policy resource. Manage policies as code by storing request bodies
and applying them with `PUT` and a stable id.
## Common failure modes
1. **Unverified destination** — writing a policy before checking the workflow; the API accepts any id.
2. **Tag missing from routing tags** — `matcher.tags` only matches tags in a rule's `metadata.routing_tags`.
3. **Accidental catch-all** — omitting `matcher` without the user confirming it.
4. **Unthrottled digest** — `all` or `per_field` without `throttle` notifies on every new alert event.
5. **Lifecycle fields in a write body** — `enabled` or `snoozed_until` in a create or update returns 400.
6. **PUT for a partial change** — removes every field left out of the body.
7. **Treating bulk 200 as success** — per-id failures are only in `errors`.
universal-matching-grouping-throttle.md 6.9 KB
# Matching, Grouping, and Throttling
How an action policy selects alerts, batches them into notification groups, and decides when each group notifies.
Operations in this reference are written in HTTP shorthand (`kbn:/...`). Run each with the `elastic` CLI command that
the [Operations](../SKILL.md#operations) table maps it to; the CLI handles authentication and headers.
## Dispatch flow
1. A rule with `kind: alert` evaluates its ES|QL query and records alerts, one per group (`group_hash`).
2. The dispatcher runs every few seconds and reads new alert events.
3. It loads every enabled action policy in the alert's space and skips policies whose `snoozed_until` is in the future.
4. **Matcher** — each policy's matcher is tested against each alert.
5. **Grouping** — matched alerts are batched per policy according to `grouping.mode`.
6. **Throttle** — each group is compared with its notification history and kept or held back.
7. **Dispatch** — each kept group is sent to every destination workflow as `inputs.payload`.
8. The workflow runs its steps (email, Slack, PagerDuty, HTTP, and so on).
## Alert status
| Status | Meaning |
| ------------ | ------------------------------------------------------------ |
| `pending` | Breached, but not yet for the rule's required number of runs |
| `active` | Firing |
| `recovering` | Breach stopped; the rule's recovery condition is not yet met |
| `inactive` | Recovered |
## Matcher
```json
{ "tags": ["<routing-tag>"], "expression": "<KQL>" }
```
### `tags`
- Matches when the alert's rule has at least one of the listed tags in `metadata.routing_tags`.
- Exact, case-sensitive match. No wildcards or prefixes.
- A rule with no routing tags never matches a policy that sets `tags`.
### `expression`
KQL evaluated against each alert. Only these fields are available:
| Field | Type | Description |
| ---------------------- | --------------------------------------------- | ---------------------------------------------------------- |
| `alert_id` | string | Alert identifier |
| `alert_status` | `inactive`, `pending`, `active`, `recovering` | Current alert status |
| `group_hash` | string | Hash of the rule's grouping values |
| `last_event_timestamp` | string | Timestamp of the most recent event |
| `severity` | `info`, `low`, `medium`, `high`, `critical` | Present when the rule query outputs a `severity` column |
| `data.*` | object | The rule's ES\|QL output row, for example `data.host.name` |
Rule identifiers and names are not in the expression context; scope by rule with `tags`. An expression that fails to
evaluate is treated as no match, so quote string values (`severity: "critical"`) and use `data.*` columns that the rule
query actually returns.
### Combining `tags` and `expression`
| `tags` | `expression` | Result |
| ------ | ------------ | ----------------------------------------------------------- |
| set | set | Both must match |
| set | absent | Routing tag match only |
| absent | set | Any rule's alerts in the space, filtered by the KQL |
| absent | absent | Catch-all: every alert in the space, including future rules |
### Matcher patterns
```json
{ "tags": ["notify-high-cpu-prod"] }
```
```json
{ "tags": ["production", "payments"] }
```
```json
{ "expression": "severity: \"critical\"" }
```
```json
{ "tags": ["production"], "expression": "severity: \"critical\" and alert_status: \"active\"" }
```
### Linking one rule to one policy
1. Read the rule with `GET kbn:/api/alerting/v2/rules/{id}` and confirm `kind` is `alert`.
2. Pick a routing tag that only this rule carries, or choose a new one that names the notification's purpose and that no
other rule carries (check with `GET kbn:/api/alerting/v2/rules` and `filter=metadata.routing_tags:"<tag>"`).
3. Update the rule with `PATCH kbn:/api/alerting/v2/rules/{id}` and
`{ "metadata": { "routing_tags": [<existing routing tags>, "<tag>"] } }`. The array is replaced whole, and a rule
holds at most 20 routing tags.
4. Create the policy with `matcher: { "tags": ["<tag>"] }`.
## Grouping modes
| Mode | Notification groups | Typical use |
| ----------- | ------------------------------------------------------- | ---------------------------------- |
| `per_alert` | One per alert (default) | Paging, incident tools, tickets |
| `all` | One per policy, containing every matching alert | A single combined summary |
| `per_field` | One per distinct combination of the listed field values | Digests per service, host, or team |
`per_field` paths resolve against the alert. Rule query columns live under `data.` (`data.service.name`); a path that
does not resolve contributes `null` to the group key, so every alert lands in the same group.
## Throttle strategies
| Strategy | Behavior | Valid with |
| --------------------- | ----------------------------------------------------------------------- | ------------------ |
| `on_status_change` | Notify when the alert status changes (default for `per_alert`) | `per_alert` |
| `per_status_interval` | Notify on status changes and again every `interval` while status holds | `per_alert` |
| `time_interval` | Notify at most once per `interval` per group | `all`, `per_field` |
| `every_time` | Notify on every dispatcher cycle that has matching alerts (high volume) | all modes |
Omitting `throttle` defaults `per_alert` to `on_status_change`. For `all` and `per_field` it applies no limit: every new
alert event notifies, as with `every_time`. Always set `time_interval` with an `interval` for these modes.
Choosing a strategy:
- Paging or ticketing tools that open and close incidents → `per_alert` + `on_status_change`.
- Reminders while an alert stays active → `per_alert` + `per_status_interval` with an interval such as `1h`.
- Periodic summaries → `per_field` or `all` + `time_interval` with an interval such as `15m` or `1h`.
- Audit or forwarding pipelines that must see every event → `every_time`.
universal-rules.md 8.3 KB
# Universal Alerting Rules
Use this reference for Universal Alerting rules (`kbn:/api/alerting/v2/rules`). A universal rule evaluates an ES|QL
query on a schedule. It carries no notification settings: alerts reach people through action policies (see
[universal-action-policies.md](universal-action-policies.md)).
Operations in this reference are written in HTTP shorthand (`kbn:/...`). Run each with the `elastic` CLI command that
the [Operations](../SKILL.md#operations) table maps it to; the CLI handles authentication and headers.
## Requirements
- **Availability** — Kibana 9.6 or later, or an Elastic Cloud Serverless Observability project (versionless), with the
`alerting:v2:enabled` advanced setting on (default). Serverless Security and Elasticsearch projects do not offer
Universal Alerting.
- **Privileges** — the **Rules** feature (`alerting_v2_rules`): `read` to list and get, `all` to write.
- **Spaces** — rules are space-scoped. Prefix paths with `kbn:/s/<space_id>/` for a non-default space.
## Choose the rule kind
`kind` is the most important decision, and it is **immutable** after creation — the update API rejects a change.
| Kind | Behavior | Use when |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `alert` | Creates an alert for each matching group and tracks it until it recovers. Alert statuses: `inactive`, `pending`, `active`, `recovering`. | The user wants to detect a problem and notify or automate a response. |
| `signal` | Stores each match as a rule event that can be queried. No alerts, no notifications. | The user wants to collect evidence or observe without being notified. |
Only `kind: alert` rules can notify. When the user wants notifications on an existing `signal` rule, explain that it
cannot be converted and offer to create a new `alert` rule with the same query and schedule.
## Rule fields
Read the operation's
[API reference page](https://www.elastic.co/docs/api/doc/kibana/operation/operation-post-alerting-v2-rules) for every
field and bound. Constraints that most often cause a rejected request:
- `recovery` and `no_data` are required when `kind` is `alert` and rejected when `kind` is `signal`.
- `metadata.routing_tags` is the only tag field action policies match, and only `alert` rules accept it. `metadata.tags`
is for filtering.
- An empty `artifacts` array is rejected: omit the field on create, or send `null` on `PATCH` to clear it.
## Write the query
- Put the data and aggregation in `query.base`, and the threshold in `query.breach.segment`. Splitting them lets
recovery and no-data strategies reuse `query.base`.
- Group with `STATS ... BY <field>` in `query.base` and list the same fields in `grouping.fields`, so each host or
service gets its own alert.
- Match field scale: ECS `system.cpu.total.pct` is fractional (`0.9` for 90%).
- Add a `severity` column to set per-alert severity, which action policies can match:
`| EVAL severity = CASE(avg_cpu > 0.95, "critical", avg_cpu > 0.8, "high", "medium")`. Valid values: `info`, `low`,
`medium`, `high`, `critical`.
## Recovery, no-data, and state transition
**Recovery** (`recovery.strategy`):
- `no_breach` — recovers when the group no longer appears in the breach results.
- `condition` — recovers when `query.base` plus `recovery.segment` returns the group, for example
`{ "strategy": "condition", "segment": "WHERE avg_cpu < 0.6" }`. Requires `query.breach`.
- `query` — recovers when a separate full ES|QL query (`recovery.query`) returns the group.
- `manual` — never recovers automatically. Omit `state_transition.recovering`, or clear it when switching an existing
rule to manual recovery; the API rejects a rule that sets both.
**No data** (`no_data.strategy`):
- `ignore` — does not check whether a group still has data.
- `keep_last` — holds the alert's current status when a group has no data.
- `resolve` — closes the alert the first time a group has no data.
Any strategy other than `ignore` needs either `query.breach` or its own `no_data.query` presence query, so a group with
no data can be told apart from one that stopped breaching.
**State transition** delays status changes to reduce noise:
- `pending.count` — consecutive matches spent in `pending` before the alert becomes `active` on the next match (`0`
opens it on the first match). `pending.timeframe` sets a duration instead; combine both with `pending.operator` (`and`
or `or`).
- `recovering.count` / `recovering.timeframe` / `recovering.operator` — the same for closing a recovered alert.
## Create a rule
Example — CPU above 90% on any host over 5 minutes, routed to on-call:
```json
{
"kind": "alert",
"metadata": {
"name": "Host CPU high",
"description": "Alerts when average CPU usage exceeds 90%.",
"tags": ["production", "infra"],
"routing_tags": ["sre-oncall"]
},
"time_field": "@timestamp",
"schedule": { "every": "1m", "lookback": "5m" },
"query": {
"base": "FROM metrics-* | STATS avg_cpu = AVG(system.cpu.total.pct) BY host.name",
"breach": { "segment": "WHERE avg_cpu > 0.9" }
},
"grouping": { "fields": ["host.name"] },
"recovery": { "strategy": "no_breach" },
"no_data": { "strategy": "keep_last" },
"state_transition": { "pending": { "count": 1 }, "recovering": { "count": 1 } }
}
```
- `POST kbn:/api/alerting/v2/rules` → server-generated id.
- `PUT kbn:/api/alerting/v2/rules/{id}` → client-supplied id; creates or replaces the rule. Its body also accepts
`enabled`: omitted, a new rule starts enabled and a replaced rule keeps its current state. `POST` rejects `enabled`
with 400, so create a rule paused with `PUT` and `"enabled": false`.
When the user names an existing action policy or a team routing tag, set `metadata.routing_tags` at creation so the rule
is routed from its first alert; see
[universal-action-policies.md](universal-action-policies.md#link-rules-and-policies-with-routing-tags).
After the write, call `GET kbn:/api/alerting/v2/rules/{id}` and report the live id, name, kind, and enabled state.
Before creating, validate the ES|QL with `POST /_query` against a short time range when the index or fields are
uncertain.
## Find and read rules
Call `GET kbn:/api/alerting/v2/rules`:
- **Filter** with KQL, for example `filter=metadata.tags:"production"` or `filter=metadata.routing_tags:"sre-oncall"`.
- **Search** free text with `search`.
- **Page** with `page` and `per_page`; **sort** with `sort_field` and `sort_order`.
Read one rule with `GET kbn:/api/alerting/v2/rules/{id}`.
## Update a rule
Prefer `PATCH kbn:/api/alerting/v2/rules/{id}` for partial changes. `kind` cannot change. Arrays such as
`metadata.routing_tags` are replaced whole — re-send the existing values when adding one. `null` clears optional fields
such as `metadata.description` and `artifacts`. Use `PUT` only to replace the whole rule. On **409**, another caller
changed the rule — re-read it and retry.
## Change lifecycle
- **Disable / enable** — `POST kbn:/api/alerting/v2/rules/{id}/_disable`;
`POST kbn:/api/alerting/v2/rules/{id}/_enable`.
- **Delete** — `DELETE kbn:/api/alerting/v2/rules/{id}`. Confirm with the user first.
- **Bulk** — send `{ "ids": [...] }` to `POST kbn:/api/alerting/v2/rules/_bulk_enable`, `_bulk_disable`, or
`_bulk_delete`. The response is 200 even when some ids fail; report `affected_count` and every entry in `errors`.
Universal rules have no snooze or mute. To silence notifications for a time, snooze the action policies that match the
rule (see [universal-action-policies.md](universal-action-policies.md)).
## Common failure modes
1. **Signal rule when notifications are wanted** — `kind` cannot change later.
2. **Missing routing tags** — action policies only match tags in `metadata.routing_tags`.
3. **Adding alert condition directly in `query.base`** — leaves recovery and no-data strategies without a breach segment
to reuse.
4. **Grouping mismatch** — `grouping.fields` that differ from the query's `BY` fields or omitting grouping fields
entirely.
5. **Routing tags overwritten** — PATCH with only the new routing tag drops the existing ones.
universal-workflow-destinations.md 17.1 KB
# Workflow Destinations
Action policies deliver notifications by scheduling Kibana Workflows. Each destination is
`{ "type": "workflow", "id": "<workflow_id>" }`, and the workflow's steps reach external systems through connectors.
Operations in this reference are written in HTTP shorthand (`kbn:/...`). Run each with the `elastic` CLI command that
the [Operations](../SKILL.md#operations) table maps it to; the CLI handles authentication and headers.
## Contents
- [Destination requirements](#destination-requirements)
- [Access and ownership](#access-and-ownership)
- [Use an existing workflow](#use-an-existing-workflow)
- [Create a new workflow](#create-a-new-workflow)
- [Dispatch payload](#dispatch-payload-inputspayload)
- [Destination workflow template](#destination-workflow-template)
- [Dry run before saving](#dry-run-before-saving)
## Destination requirements
The action policy API accepts any workflow id without checking it, so a broken destination surfaces only at dispatch
time, as a lost notification. Every destination, new or existing, must meet these requirements:
| Requirement | What breaks without it |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Exists in the policy's space, with `enabled` and `valid` `true` | The dispatcher skips a missing or disabled workflow. Kibana saves a workflow that fails validation as disabled. |
| `definition.triggers` has exactly one `manual` trigger whose `inputs` declare `payload` with `$ref: '#/kibana/definitions/alertingV2NotificationGroup'` and require no other inputs | Policies schedule the workflow with `{ payload }` as its inputs; a declaration that rejects it fails the run. The `$ref` also lets the Workflows editor flag `inputs.payload.*` references that do not exist; saving does not run that check, so a `valid` workflow can still render empty fields. |
| `permissions.execute` is `true` for the user who will own the policy | The owner cannot schedule the workflow (see [Access and ownership](#access-and-ownership)). |
| Every `connector-id` in its steps resolves for that user with `GET kbn:/api/actions/connector/{id}` | Connector steps run as the owner and fail with `Unauthorized to execute`. |
| No top-level `workflow.execute` or `workflow.executeAsync` step without an `if` uses `run-as-mode: inherit` while `definition.settings.run_as` is unset | The workflow can run only under a parent workflow, so scheduling it from a policy is refused. |
Make steps idempotent: delivery is at-least-once, so the same group can be dispatched more than once.
## Access and ownership
Create, upsert (`PUT`), update (`PATCH`), and key rotation (`_update_api_key`, `_bulk_update_api_key`) all make the
caller the policy's API key owner. At dispatch time, workflows are fetched and scheduled as that owner, and the
workflow's own access control decides what the owner can do. The `permissions` object in
`GET kbn:/api/workflows/workflow/{id}` reports this for the caller, so check it as the user who will own the policy:
- A public workflow (the default) can be read and run by the owner.
- A private workflow can be read only when the owner is its creator or holds a viewer, executor, or editor entry, and
run only as creator, executor, or editor. A workflow the owner cannot read is skipped as not found; one the owner can
read but not run fails to schedule.
Workflow steps also run as the owner. Connector steps need **Read** on the **Actions and Connectors** feature in the
policy's space.
## Use an existing workflow
For a workflow the user names, or one already on the policy (for key rotation, read the policy first with
`GET kbn:/api/alerting/v2/action_policies/{id}` to get its destinations), make these calls for each destination before
any policy write:
1. **Read the workflow** with `GET kbn:/api/workflows/workflow/{id}` and check the response: `enabled` and `valid` are
`true`; `definition.triggers` has exactly one `manual` trigger whose `payload` input references
`#/kibana/definitions/alertingV2NotificationGroup`; `permissions.execute` is `true`; and no top-level
`workflow.execute` or `workflow.executeAsync` step without an `if` uses `run-as-mode: inherit` while
`definition.settings.run_as` is unset.
2. **Check each connector** the workflow uses: for every `connector-id` in its steps, call
`GET kbn:/api/actions/connector/{id}` as the user who will own the policy. A connector that does not resolve for that
user makes the step fail at dispatch time.
3. **Stop if any check fails.** Ask the user for the correct workflow or the missing privilege or share, or create a new
workflow. Never write a policy that points at a workflow that does not meet the requirements.
These checks do not cover Liquid references; when the user wants proof that the template renders, dry-run the workflow's
YAML with each notifying step replaced by a `type: console` step (see [Dry run before saving](#dry-run-before-saving)).
Changing what an existing workflow sends is workflow authoring; leave it to the `kibana-workflows` skill and re-check
the requirements before the next policy write.
## Create a new workflow
Create a dedicated workflow when the user names none. The message depends on the policy's rules and their query columns.
1. **Find a connector** of the requested type with `GET kbn:/api/workflows/connectors`. If none fits, stop and tell the
user a connector must be configured first.
2. **Draft the workflow** with its notification as `type: console` steps and the standard message from the
[template](#destination-workflow-template), using the `kibana-workflows` skill if it is available. Keep one `manual`
trigger whose `payload` input references `#/kibana/definitions/alertingV2NotificationGroup`, and read only
`inputs.payload.*` fields and `data.*` columns that the matched rules' queries return (read them with
`GET kbn:/api/alerting/v2/rules/{id}`, or for a routing tag, `GET kbn:/api/alerting/v2/rules` with
`filter=metadata.routing_tags:"<tag>"`). The console steps print every templated field the connector step will send,
such as an email's subject and body. Name the workflow `Notify: <policy name>`.
3. **Dry-run the console draft** with `POST kbn:/api/workflows/test` (see
[Dry run before saving](#dry-run-before-saving)). Fix validation errors, input errors, and empty rendered fields, and
re-run until the output is right. If the caller lacks the Workflows **Execute** privilege (403), skip the dry run and
say so.
4. **Swap in the connector step.** Replace the `console` steps with the connector's step: its `type`, `connector-id`,
and `with` fields from `GET kbn:/api/workflows/schema`. Move the tested Liquid text into the matching `with` fields
unchanged; if a template has to change, dry-run the console version again first. Do not dry-run the result, because
it would send a real notification.
5. **Save it enabled** with `POST kbn:/api/workflows/workflow` and the body `{ "yaml": "<workflow YAML>" }`, and confirm
`valid: true` and `enabled: true` in the response. Save it enabled even though the `kibana-workflows` skill saves new
side-effecting workflows disabled: a disabled destination drops every notification. An invalid workflow is still
saved, disabled; correct it with `PUT kbn:/api/workflows/workflow/{id}` and the same body, whose response lists
`validationErrors`. The caller created the workflow and took its connector from their own connector list, so the
ownership and connector requirements already hold.
## Dispatch payload (`inputs.payload`)
| Field | Type | Description |
| ---------- | -------- | --------------------------------------------------------------------------- |
| `id` | string | Notification group identifier |
| `policyId` | string | Id of the action policy that dispatched the group |
| `groupKey` | object | Grouping key (shape depends on the grouping mode) |
| `alerts` | object[] | Alerts in the group |
| `rules` | object | Rule metadata keyed by rule id; read names with `rules[alert.rule_id].name` |
Each entry in `alerts`:
| Field | Type | Description |
| ---------------------- | ------------ | ----------------------------------------------------- |
| `alert_id` | string | Alert identifier |
| `alert_status` | string | `inactive`, `pending`, `active`, or `recovering` |
| `alert_url` | string | Absolute URL of the alert details page |
| `group_hash` | string | Hash of the rule's grouping values |
| `last_event_timestamp` | string | Timestamp of the most recent event |
| `rule_id` | string, null | Rule that produced the alert |
| `source` | string | Origin of the alert events |
| `space_id` | string | Space of the alert |
| `severity` | string | Optional: `info`, `low`, `medium`, `high`, `critical` |
| `data` | object | Optional: the rule's ES\|QL output row |
Liquid usage:
- Top-level fields: `{{ inputs.payload.policyId }}`.
- Iterate alerts: `{% for alert in inputs.payload.alerts %}…{% endfor %}`.
- Rule name: `{{ inputs.payload.rules[alert.rule_id].name }}`.
- Query columns use nested paths (`alert.data.host.name`). `data` can be empty for recovering or inactive alerts, so
guard with `| default: "n/a"` or `{% if alert.data %}`.
- Include `{{ alert.alert_url }}` in every notification so recipients can open the alert.
When one workflow serves policies that match several rules, keep the template generic (rule name, status, URL, guarded
`data` fields). Use separate workflows when rules need different message shapes.
## Destination workflow template
Email workflow with the standard Kibana notification message: one block per alert with the rule name, status, severity,
last event time, a link to the alert, and the alert id, plus a count header when the group has more than one alert. It
reads only `inputs.payload.*` fields, so it works for any rule. To show a column the matched rules' queries return, add
a line after `Alert id`, for example `Host: {{ alert.data.host.name | default: "unknown" }}`; never reference a column
they do not return. The email step renders `message` as Markdown: `**…**` is bold, `[text](url)` is a link, and a
trailing `\` is a line break. Keep them; the dry run's console output shows this raw Markdown.
Only the `triggers` block carries over unchanged to every destination. For other channels (for example Slack or
PagerDuty), replace the whole step: the step type, `connector-id`, and `with` fields all differ per connector, and
`GET kbn:/api/workflows/schema` lists them for the connectors in the space. Keep the same message content in the
channel's markup; for Slack, follow the
[Alert Notification Group to Slack](https://github.com/elastic/workflows/tree/main/library/workflows/alert-notification-group-slack)
library workflow.
```yaml
version: "1"
name: "Notify: payments errors"
enabled: true
triggers:
- type: manual
inputs:
properties:
payload:
$ref: "#/kibana/definitions/alertingV2NotificationGroup"
steps:
- name: send_email
type: email
connector-id: <email-connector-id>
with:
to:
- oncall@example.com
subject: "Alert: {{ inputs.payload.alerts | size }} alert(s)"
message: |
{%- assign alert_count = inputs.payload.alerts | size -%}
{%- if alert_count > 1 -%}
**{{ alert_count }} alerts**
{% endif -%}
{%- for alert in inputs.payload.alerts -%}
**{{ inputs.payload.rules[alert.rule_id].name | default: "Unnamed rule" }}** — {{ alert.alert_status | capitalize }}{% if alert.severity %} · {{ alert.severity | capitalize }}{% endif %}\
Last event {{ alert.last_event_timestamp | date: "%Y-%m-%d %H:%M UTC", 0 }} · [View in app]({{ alert.alert_url }})\
Alert id: {{ alert.alert_id }}
{% unless forloop.last %}
{% endunless -%}
{%- endfor -%}
```
## Dry run before saving
`POST kbn:/api/workflows/test` runs every step, even in test mode. Draft the notifying step as `console` first, printing
every templated field the connector step will send, and dry-run that draft. Send the draft as `workflowYaml`, without
`workflowId` (nothing is saved). Replace it with the connector step from the template above only after the output is
right, moving each tested text into the matching `with` field (`subject`, `message`) unchanged. Print the subject from
its own step, because the message's leading `{%-` strips the whitespace before it:
```yaml
steps:
- name: print_subject
type: console
with:
message: "Alert: {{ inputs.payload.alerts | size }} alert(s)"
- name: print_message
type: console
with:
message: |
{%- assign alert_count = inputs.payload.alerts | size -%}
{%- if alert_count > 1 -%}
**{{ alert_count }} alerts**
{% endif -%}
{%- for alert in inputs.payload.alerts -%}
**{{ inputs.payload.rules[alert.rule_id].name | default: "Unnamed rule" }}** — {{ alert.alert_status | capitalize }}{% if alert.severity %} · {{ alert.severity | capitalize }}{% endif %}\
Last event {{ alert.last_event_timestamp | date: "%Y-%m-%d %H:%M UTC", 0 }} · [View in app]({{ alert.alert_url }})\
Alert id: {{ alert.alert_id }}
{% unless forloop.last %}
{% endunless -%}
{%- endfor -%}
```
Send it with a sample notification group shaped like a real dispatch:
```json
{
"workflowYaml": "<YAML with console steps>",
"inputs": {
"payload": {
"id": "sample-group",
"policyId": "sample-policy",
"groupKey": {},
"alerts": [
{
"alert_id": "sample-alert",
"alert_status": "active",
"alert_url": "https://kibana.example.com/app/alerts/sample-alert",
"group_hash": "sample-hash",
"last_event_timestamp": "2026-01-01T00:00:00.000Z",
"rule_id": "sample-rule",
"source": "internal",
"space_id": "default",
"severity": "critical",
"data": { "host": { "name": "web-01" }, "error_count": 12 }
}
],
"rules": { "sample-rule": { "name": "Payments errors" } }
}
}
}
```
Read the outcome with `GET kbn:/api/workflows/executions/{executionId}` and
`GET kbn:/api/workflows/executions/{executionId}/logs`
([API reference](https://www.elastic.co/docs/api/doc/kibana/operation/operation-post-workflows-test)). What it means for
a policy destination:
- An input validation error means the trigger inputs reject `{ payload }`.
- An empty value, or a `default` fallback for a field the sample payload sets, means a Liquid path does not exist in the
payload or in the rule's columns. `Unnamed rule` is expected only for an alert without a `rule_id`; with the sample
above, it means the `rules` lookup is wrong.
The dry run needs the Workflows **Execute** privilege. It runs as the caller, so it does not prove the policy owner's
connector access.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE