Use configuration files to provision alerting resources
Управляйте вашими ресурсами оповещений с помощью файлов конфигурации, которые можно версионировать. При запуске Grafana провижинит ресурсы, определённые в ваших файлах конфигурации. Провижининг может создавать, обновлять или удалять существующие ресурсы в вашем экземпляре Grafana.
Это руководство описывает шаги и ссылки для провижининга ресурсов оповещений с помощью файлов YAML. Для практической демонстрации вы можете клонировать и попробовать этот пример с использованием Grafana OSS и Docker Compose.
Note
Провижининг Grafana с помощью файлов конфигурации недоступен в Grafana Cloud.
Вы не можете редактировать провижиненные из файлов ресурсы в Grafana. Вы можете изменить свойства ресурса только путём изменения файла провижининга и перезапуска Grafana или выполнения горячей перезагрузки. Это предотвращает внесение изменений в ресурс, которые были бы перезаписаны, если файл будет провижинен снова или будет выполнена горячая перезагрузка.
Провижининг с помощью файлов конфигурации выполняется во время первоначальной настройки вашей системы Grafana, но вы можете запустить его повторно в любое время с помощью Grafana Admin API.
Импорт существующего ресурса оповещений приводит к конфликту. Сначала, если они есть, удалите ресурсы, которые планируете импортировать.
Детали того, как настроить файлы и какие поля обязательны для каждого объекта, перечислены ниже в зависимости от того, какой ресурс вы провижините.
Import alert rules
Создавайте или удаляйте правила оповещения с помощью файлов провижининга в вашем экземпляре (или экземплярах) Grafana.
-
Найдите группу правил оповещения в Grafana.
-
Экспортируйте и скачайте файл провижининга для ваших правил оповещения.
-
Скопируйте содержимое в файл конфигурации YAML или JSON и добавьте его в каталог
provisioning/alertingэкземпляра Grafana, в который хотите импортировать ресурсы оповещений.Примеры файлов конфигурации приведены ниже.
-
Перезапустите ваш экземпляр Grafana (или перезагрузите провижиненные файлы с помощью Admin API).
Ниже приведён пример файла конфигурации для создания правил оповещения.
# config file version
apiVersion: 1
# List of rule groups to import or update
groups:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the rule group
name: my_rule_group
# <string, required> name of the folder the rule group will be stored in
folder: my_first_folder
# <duration, required> interval that the rule group should evaluated at
interval: 60s
# <list, required> list of rules that are part of the rule group
rules:
# <string, required> unique identifier for the rule. Should not exceed 40 symbols. Only letters, numbers, - (hyphen), and _ (underscore) allowed.
- uid: my_id_1
# <string, required> title of the rule that will be displayed in the UI
title: my_first_rule
# <string, required> which query should be used for the condition
condition: A
# <list, required> list of query objects that should be executed on each
# evaluation - should be obtained through the API
data:
- refId: A
datasourceUid: '__expr__'
model:
conditions:
- evaluator:
params:
- 3
type: gt
operator:
type: and
query:
params:
- A
reducer:
type: last
type: query
datasource:
type: __expr__
uid: '__expr__'
expression: 1==0
intervalMs: 1000
maxDataPoints: 43200
refId: A
type: math
# <string> UID of a dashboard that the alert rule should be linked to
dashboardUid: my_dashboard
# <int> ID of the panel that the alert rule should be linked to
panelId: 123
# <string> the state the alert rule will have when no data is returned
# possible values: "NoData", "Alerting", "OK", default = NoData
noDataState: Alerting
# <string> the state the alert rule will have when the query execution
# failed - possible values: "Error", "Alerting", "OK"
# default = Alerting
execErrState: Alerting
# <duration, required> for how long should the alert fire before alerting
for: 60s
# <map<string, string>> a map of strings to pass around any data
annotations:
some_key: some_value
# <map<string, string> a map of strings that can be used to filter and
# route alerts
labels:
team: sre_team_1
Ниже приведён пример файла конфигурации для удаления правил оповещения.
# config file version
apiVersion: 1
# List of alert rule UIDs that should be deleted
deleteRules:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> unique identifier for the rule
uid: my_id_1
Import contact points
Создавайте или удаляйте contact points с помощью файлов провижининга в вашем экземпляре (или экземплярах) Grafana.
-
Найдите contact point в Grafana.
-
Экспортируйте и скачайте файл провижининга для вашего contact point.
-
Скопируйте содержимое в файл конфигурации YAML или JSON и добавьте его в каталог
provisioning/alertingэкземпляра Grafana, в который хотите импортировать ресурсы оповещений.Примеры файлов конфигурации приведены ниже.
-
Перезапустите ваш экземпляр Grafana (или перезагрузите провижиненные файлы с помощью Admin API).
Ниже приведён пример файла конфигурации для создания contact points.
# config file version
apiVersion: 1
# List of contact points to import or update
contactPoints:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the contact point
name: cp_1
receivers:
# <string, required> unique identifier for the receiver. Should not exceed 40 symbols. Only letters, numbers, - (hyphen), and _ (underscore) allowed.
- uid: first_uid
# <string, required> type of the receiver
type: prometheus-alertmanager
# <bool, optional> Disable the additional [Incident Resolved] follow-up alert, default = false
disableResolveMessage: false
# <object, required> settings for the specific receiver type
settings:
url: http://test:9000
Ниже приведён пример файла конфигурации для удаления contact points.
# config file version
apiVersion: 1
# List of receivers that should be deleted
deleteContactPoints:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> unique identifier for the receiver
uid: first_uid
Settings
Ниже приведены некоторые примеры настроек, которые вы можете использовать для различных интеграций contact points.
Alertmanager
type: prometheus-alertmanager
settings:
# <string, required>
url: http://localhost:9093
# <string>
basicAuthUser: abc
# <string>
basicAuthPassword: abc123
DingDing
type: dingding
settings:
# <string, required>
url: https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxx
# <string> options: link, actionCard
msgType: link
# <string>
message: |
{{ template "default.message" . }}
Discord
type: discord
settings:
# <string, required>
url: https://discord/webhook
# <string>
avatar_url: https://my_avatar
# <bool>
use_discord_username: false
# <string>
message: |
{{ template "default.message" . }}
type: email
settings:
# <string, required>
addresses: me@example.com;you@example.com
# <bool>
singleEmail: false
# <string>
message: my optional message to include
# <string>
subject: |
{{ template "default.title" . }}
Google Chat
type: googlechat
settings:
# <string, required>
url: https://google/webhook
# <string>
message: |
{{ template "default.message" . }}
Kafka
type: kafka
settings:
# <string, required>
kafkaRestProxy: http://localhost:8082
# <string, required>
kafkaTopic: topic1
LINE
type: line
settings:
# <string, required>
token: xxx
MQTT
type: mqtt
settings:
# <string, required>
brokerUrl: tcp://127.0.0.1:1883
# <string>
clientId: grafana
# <string, required>
topic: grafana/alerts
# <string>
messageFormat: json
# <string>
username: grafana
# <string>
password: password1
# <string>
qos: 0
# <bool>
retain: false
# <map>
tlsConfig:
# <bool>
insecureSkipVerify: false
# <string>
clientCertificate: certificate in PEM format
# <string>
clientKey: key in PEM format
# <string>
caCertificate: CA certificate in PEM format
Microsoft Teams
type: teams
settings:
# <string, required>
url: https://ms_teams_url
# <string>
title: |
{{ template "default.title" . }}
# <string>
sectiontitle: ''
# <string>
message: |
{{ template "default.message" . }}
OpsGenie
type: opsgenie
settings:
# <string, required>
apiKey: xxx
# <string, required>
apiUrl: https://api.opsgenie.com/v2/alerts
# <string>
message: |
{{ template "default.title" . }}
# <string>
description: some descriptive description
# <bool>
autoClose: false
# <bool>
overridePriority: false
# <string> options: tags, details, both
sendTagsAs: both
PagerDuty
type: pagerduty
settings:
# <string, required> the 32-character Events API key https://support.pagerduty.com/docs/api-access-keys#events-api-keys
integrationKey: XXX
# <string> options: critical, error, warning, info
severity: critical
# <string>
class: ping failure
# <string>
component: Grafana
# <string>
group: app-stack
# <string>
summary: |
{{ template "default.message" . }}
Pushover
type: pushover
settings:
# <string, required>
apiToken: XXX
# <string, required>
userKey: user1,user2
# <string>
device: device1,device2
# <string> options (high to low): 2,1,0,-1,-2
priority: '2'
# <string>
retry: '30'
# <string>
expire: '120'
# <string> the number of seconds before a message expires and is deleted automatically. Examples: 10s, 5m30s, 8h.
ttl:
# <string>
sound: siren
# <string>
okSound: magic
# <string>
message: |
{{ template "default.message" . }}
Slack
type: slack
settings:
# <string, required>
recipient: alerting-dev
# <string, required>
token: xxx
# <string>
username: grafana_bot
# <string>
icon_emoji: heart
# <string>
icon_url: https://icon_url
# <string>
mentionUsers: user_1,user_2
# <string>
mentionGroups: group_1,group_2
# <string> options: here, channel
mentionChannel: here
# <string> Optionally provide a Slack incoming webhook URL for sending messages, in this case the token isn't necessary
url: https://some_webhook_url
# <string>
endpointUrl: https://custom_url/api/chat.postMessage
# <string>
color: {{ if eq .Status "firing" }}#D63232{{ else }}#36a64f{{ end }}
# <string>
title: |
{{ template "slack.default.title" . }}
text: |
{{ template "slack.default.text" . }}
Sensu Go
type: sensugo
settings:
# <string, required>
url: http://sensu-api.local:8080
# <string, required>
apikey: xxx
# <string>
entity: default
# <string>
check: default
# <string>
handler: some_handler
# <string>
namespace: default
# <string>
message: |
{{ template "default.message" . }}
Telegram
type: telegram
settings:
# <string, required>
bottoken: xxx
# <string, required>
chatid: some_chat_id
# <string>
message: |
{{ template "default.message" . }}
Threema Gateway
type: threema
settings:
# <string, required>
api_secret: xxx
# <string, required>
gateway_id: A5K94S9
# <string, required>
recipient_id: A9R4KL4S
VictorOps
type: victorops
settings:
# <string, required>
url: XXX
# <string> options: CRITICAL, WARNING
messageType: CRITICAL
Webhook
type: webhook
settings:
# <string, required>
url: https://endpoint_url
# <string> options: POST, PUT
httpMethod: POST
# <string>
username: abc
# <string>
password: abc123
# <string>
authorization_scheme: Bearer
# <string>
authorization_credentials: abc123
# <string>
maxAlerts: '10'
# <map>
tlsConfig:
# <bool>
insecureSkipVerify: false
# <string>
clientCertificate: certificate in PEM format
# <string>
clientKey: key in PEM format
# <string>
caCertificate: CA certificate in PEM format
hmacConfig:
#<string>
secret: secret-key
#<string>
header: X-Grafana-Alerting-Signature
#<string>
timestampHeader: X-Grafana-Alerting-Signature-Timestamp
WeCom
type: wecom
settings:
# <string, required>
url: https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx
# <string>
message: |
{{ template "default.message" . }}
# <string>
title: |
{{ template "default.title" . }}
Import notification template groups
Создавайте или удаляйте группы шаблонов уведомлений с помощью файлов провижининга в вашем экземпляре (или экземплярах) Grafana.
-
Найдите группу шаблонов уведомлений в Grafana.
-
Экспортируйте группу шаблонов, скопировав содержимое шаблона и его имя.
-
Скопируйте содержимое в файл конфигурации YAML или JSON и добавьте его в каталог
provisioning/alertingэкземпляра Grafana, в который хотите импортировать ресурсы оповещений.Примеры файлов конфигурации приведены ниже.
-
Перезапустите ваш экземпляр Grafana (или перезагрузите провижиненные файлы с помощью Admin API).
Ниже приведён пример файла конфигурации для создания групп шаблонов уведомлений.
# config file version
apiVersion: 1
# List of templates to import or update
templates:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the template group, must be unique
name: my_first_template
# <string, required> content of the template group
template: |
{{ define "my_first_template" }}
Custom notification message
{{ end }}
Ниже приведён пример файла конфигурации для удаления групп шаблонов уведомлений.
# config file version
apiVersion: 1
# List of alert rule UIDs that should be deleted
deleteTemplates:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the template group, must be unique
name: my_first_template
Import notification policies
Создавайте или сбрасывайте дерево политик уведомлений с помощью файлов провижининга в вашем экземпляре (или экземплярах) Grafana.
В Grafana всё дерево политик уведомлений рассматривается как единый крупный ресурс. Добавляйте новые конкретные политики как подполитики под корневой политикой. Поскольку конкретные политики могут зависеть друг от друга, вы не можете провижинить подмножества дерева политик; всё дерево должно быть определено в одном месте.
Warning
Since the policy tree is a single resource, provisioning it will overwrite all policies in the notification policy tree. However, it does not affect internal policies created when alert rules directly select a contact point.
-
Найдите дерево политик уведомлений в Grafana.
-
Экспортируйте и скачайте файл провижининга для вашего дерева политик уведомлений.
-
Скопируйте содержимое в файл конфигурации YAML или JSON и добавьте его в каталог
provisioning/alertingэкземпляра Grafana, в который хотите импортировать ресурсы оповещений.Примеры файлов конфигурации приведены ниже.
-
Перезапустите ваш экземпляр Grafana (или перезагрузите провижиненные файлы с помощью Admin API).
Ниже приведён пример файла конфигурации для создания политик уведомлений.
# config file version
apiVersion: 1
# List of notification policies
policies:
# <int> organization ID, default = 1
- orgId: 1
# <string> name of the contact point that should be used for this route
receiver: grafana-default
# <list> The labels by which incoming alerts are grouped together. For example,
# multiple alerts coming in for cluster=A and alertname=LatencyHigh would
# be batched into a single group.
#
# To aggregate by all possible labels use the special value '...' as
# the sole label name, for example:
# group_by: ['...']
# This effectively disables aggregation entirely, passing through all
# alerts as-is. This is unlikely to be what you want, unless you have
# a very low alert volume or your upstream notification system performs
# its own grouping.
group_by: ['...']
# <list> a list of prometheus-like matchers that an alert rule has to fulfill to match the node (allowed chars
# [a-zA-Z_:])
matchers:
- alertname = Watchdog
- service_id_X = serviceX
- severity =~ "warning|critical"
# <list> a list of grafana-like matchers that an alert rule has to fulfill to match the node
object_matchers:
- ['alertname', '=', 'CPUUsage']
- ['service_id-X', '=', 'serviceX']
- ['severity', '=~', 'warning|critical']
# <list> Times when the route should be muted. These must match the name of a
# mute time interval.
# Additionally, the root node cannot have any mute times.
# When a route is muted it will not send any notifications, but
# otherwise acts normally (including ending the route-matching process
# if the `continue` option is not set)
mute_time_intervals:
- abc
# <duration> How long to initially wait to send a notification for a group
# of alerts. Allows to collect more initial alerts for the same group.
# (Usually ~0s to few minutes), default = 30s
group_wait: 30s
# <duration> How long to wait before sending a notification about new alerts that
# are added to a group of alerts for which an initial notification has
# already been sent. (Usually ~5m or more), default = 5m
group_interval: 5m
# <duration> How long to wait before sending a notification again if it has already
# been sent successfully for an alert. (Usually ~3h or more), default = 4h
repeat_interval: 4h
# <list> Zero or more child policies. The schema is the same as the root policy.
# routes:
# # Another recursively nested policy...
# - receiver: another-receiver
# matchers:
# - ...
# ...
Ниже приведён пример файла конфигурации для сброса дерева политик к значению по умолчанию:
# config file version
apiVersion: 1
# List of orgIds that should be reset to the default policy
resetPolicies:
- 1
Import mute timings
Создавайте или удаляйте mute timings через файлы провижининга в вашем экземпляре (или экземплярах) Grafana.
-
Найдите mute timing в Grafana.
-
Экспортируйте и скачайте файл провижининга для вашего mute timing.
-
Скопируйте содержимое в файл конфигурации YAML или JSON и добавьте его в каталог
provisioning/alertingэкземпляра Grafana, в который хотите импортировать ресурсы оповещений.Примеры файлов конфигурации приведены ниже.
-
Перезапустите ваш экземпляр Grafana (или перезагрузите провижиненные файлы с помощью Admin API).
Ниже приведён пример файла конфигурации для создания mute timings.
# config file version
apiVersion: 1
# List of mute time intervals to import or update
muteTimes:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the mute time interval, must be unique
name: mti_1
# <list> time intervals that should trigger the muting
# refer to https://prometheus.io/docs/alerting/latest/configuration/#time_interval-0
time_intervals:
- times:
- start_time: '06:00'
end_time: '23:59'
location: 'UTC'
weekdays: ['monday:wednesday', 'saturday', 'sunday']
months: ['1:3', 'may:august', 'december']
years: ['2020:2022', '2030']
days_of_month: ['1:5', '-3:-1']
Ниже приведён пример файла конфигурации для удаления mute timings.
# config file version
apiVersion: 1
# List of mute time intervals that should be deleted
deleteMuteTimes:
# <int> organization ID, default = 1
- orgId: 1
# <string, required> name of the mute time interval, must be unique
name: mti_1
Template variable interpolation
Провижининг подставляет значения переменных окружения, используя синтаксис $variable.
contactPoints:
- orgId: 1
name: My Contact Email Point
receivers:
- uid: 1
type: email
settings:
addresses: $EMAIL
В этом примере провижининг заменяет $EMAIL на значение переменной окружения EMAIL или на пустую строку, если она отсутствует. Дополнительную информацию см. в разделе
Использование переменных окружения в документации по провижинингу.
В ресурсах оповещений большинство свойств поддерживают подстановку переменных, за несколькими исключениями:
- Аннотации правил оповещения:
groups[].rules[].annotations - Диапазон времени правил оповещения:
groups[].rules[].relativeTimeRange - Модель запроса правил оповещения:
groups[].rules[].data.model - Имя mute timings:
muteTimes[].name - Интервалы времени mute timings:
muteTimes[].time_intervals[] - Имя группы шаблонов уведомлений:
templates[].name - Содержимое группы шаблонов уведомлений:
templates[].template
Обратите внимание, что для свойств, поддерживающих подстановку, вы можете неожиданно подставить переменные шаблона, когда это не предполагалось. Чтобы избежать этого, вы можете экранировать $variable с помощью $$variable.
Например, при провижининге свойства subject в объекте contactPoints.receivers.settings, которое должно использовать переменную $labels.
subject: '{{ $labels }}'выполнит подстановку, некорректно определив subject какsubject: '{{ }}'.subject: '{{ $$labels }}'не выполнит подстановку, корректно определив subject какsubject: '{{ $labels }}'.
More examples
Дополнительные примеры по концепции этого руководства:
- Попробуйте провижининг ресурсов оповещений в Grafana OSS с помощью файлов YAML через демонстрационный проект с использованием Docker Compose или развёртываний в Kubernetes.
- Ознакомьтесь с различными опциями того, как Grafana провижинит ресурсы, в документации по провижинингу Grafana.
- Для поддержки Helm ознакомьтесь с примерами провижининга ресурсов оповещений в документации Grafana Helm Chart.