- FastAPI приложение для отправки мониторинговых алертов в мессенджеры - Поддержка Telegram и MAX/VK - Интеграция с Grafana, Zabbix, AlertManager - Автоматическое создание тикетов в Jira - Управление группами мессенджеров через API - Декораторы для авторизации и скрытия эндпоинтов - Подробная документация в папке docs/ Автор: Сергей Антропов Сайт: https://devops.org.ru
7.7 KiB
7.7 KiB
Шаблоны сообщений
Структура шаблонов
Шаблоны сообщений находятся в папке templates/ и используют синтаксис Jinja2. Шаблоны разделены на две категории:
- Шаблоны для мессенджеров - форматирование сообщений для отправки в Telegram, MAX/VK
- Шаблоны для Jira - форматирование описания тикетов в Jira
Шаблоны для мессенджеров
Grafana (templates/grafana.tmpl)
Шаблон для форматирования алертов из Grafana:
{{ alert_icon }} <b>{{ title }}</b>
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }}{% endif %}
<b>Подробнее:</b>
{{ message }}
{% if labels %}
👉 <b>Переменные:</b>
{{ labels }}{% endif %}
{% if tags and state !='ok' %}💻 <b>Ответственные:</b>
{{ tags }}{% endif %}
Доступные переменные:
alert_icon- иконка алерта (🔴, 🟢, 🟡, 🟠, 🔵)status_icon- иконка статуса (💀, ✅, 🐢, 🤷, 🥴)status_name- название статусаtitle- заголовок алертаmessage- сообщение алертаstate- состояние алерта (alerting, ok, paused, pending, no_data)labels- метрики (evalMatches)tags- теги алерта
Zabbix (templates/zabbix.tmpl)
Шаблон для форматирования алертов из Zabbix:
{{ alert_icon }} <b>{{ title }}</b>
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }} ({{ state }}){% endif %}
<b>Кратко:</b>
{{ subject }}
<b>Подробнее:</b>
{{ message }}
👉 <b>Значение:</b>
{{ message_data }}
🌐 <b>Сеть:</b>
Хост: {{ label_host }}
IP: {{ label_ip }}
Порт: {{ label_port }}
Доступные переменные:
alert_icon- иконка алертаstatus_icon- иконка статусаstatus_name- название статусаtitle- название событияsubject- тема алертаmessage- сообщение алертаmessage_data- дополнительные данные событияlabel_host- имя хостаlabel_ip- IP адрес хостаlabel_port- порт хоста
AlertManager (templates/alertmanager.tmpl)
Шаблон для форматирования алертов из AlertManager:
{{ alert_icon }} <b>{{ alertname }}</b>
{% if summary is defined %}{{ summary }}{% endif %}
{% if status_name is defined %}{{ status_icon }} <b>Критичность</b>: {{ status_name }}{% endif %}{% if description is defined %}
<b>Подробнее:</b>
{{ description }}{% endif %}{% if another_annotations != "" %}
{{ another_annotations }}{% endif %}
{% if clustername is defined %}👉 <b>Kubernetes:</b>
<b>Кластер</b>: {{ clustername }}{% if node is defined %}
<b>Нода</b>: {{ node }}{% endif %}{% if ns is defined %}
<b>Неймспейс</b>: {{ ns }}{% endif %}{% if deployment is defined %}
<b>Деплоймент</b>: {{ deployment }}{% endif %}{% if daemonset is defined %}
<b>Демонсет</b>: {{ daemonset }}{% endif %}{% if replicaset is defined %}
<b>Репликасет</b>: {{ replicaset }}{% endif %}{% if statefulset is defined %}
<b>Стейтфулсет</b>: {{ statefulset }}{% endif %}{% if container is defined %}
<b>Контейнер</b>: {{ container }}{% endif %}{% if pod is defined %}
<b>Под</b>: {{ pod }}{% endif %}{% if persistentvolumeclaim is defined %}
<b>PVC</b>: {{ persistentvolumeclaim }}{% endif %}{% if job_name is defined %}
<b>Имя джобы</b>: {{ job_name }}{% endif %}{% if job is defined %}
<b>Джоба</b>: {{ job }}{% endif %}{% if reason is defined %}
<b>Причина</b>: {{ reason }}{% endif %}{% if endpoint is defined %}
<b>Эндпоинт</b>: {{ endpoint }}{% endif %}{% if instance is defined %}
<b>Инстанс</b>: {{ instance }}{% endif %}{% if condition is defined %}
<b>Состояние</b>: {{ condition }}{% endif %}{% if reason is defined %}
<b>Причина</b>: {{ reason }}{% endif %}{% endif %}
{% if prometheus is defined %}🔍 <b>Прометей:</b>
<b>Сервер</b>: {{ prometheus }}{% if service is defined %}
<b>Сервис</b>: {{ service }}{% endif %}{% if metrics_path is defined %}
<b>Метрики</b>: {{ metrics_path }}{% endif %}{% if uid is defined %}
<b>UID</b>: {{ uid }}{% endif %}{% if integration is defined %}
<b>Integration</b>: {{ integration }}{% endif %}{% if To is defined %}
<b>To</b>: {{ integration }}{% endif %}{% endif %}
{% if another_labels != "" %}
🤷 <b>Разное</b>:
{{ another_labels }}{% endif %}
Доступные переменные:
alert_icon- иконка алертаstatus_icon- иконка статусаstatus_name- название статусаalertname- название алертаsummary- краткое описаниеdescription- подробное описаниеanother_annotations- дополнительные аннотацииclustername- имя кластера Kubernetesnode- имя нодыns- namespacedeployment- имя deploymentpod- имя podcontainer- имя контейнера- И другие метки из
commonLabels
Шаблоны для Jira
Общий шаблон (templates/jira_common.tmpl)
Шаблон для форматирования описания тикетов в Jira:
**Источник:** {{ source }}
{% if k8s_cluster %}**Kubernetes кластер:** {{ k8s_cluster }}{% endif %}
---
## Детали алерта
{% if source == "alertmanager" %}
**Статус:** {{ status }}
**Название:** {{ alertname }}
**Критичность:** {{ severity }}
{% if summary %}**Краткое описание:**
{{ summary }}
{% endif %}
{% if description %}**Подробное описание:**
{{ description }}
{% endif %}
**Метки:**
{% for key, value in common_labels.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
**Аннотации:**
{% for key, value in common_annotations.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
{% endif %}
{% if source == "grafana" %}
**Состояние:** {{ state }}
**Правило:** {{ ruleName }}
**Заголовок:** {{ title }}
{% if message %}**Сообщение:**
{{ message }}
{% endif %}
{% if tags %}**Теги:**
{% for key, value in tags.items() %}
- *{{ key }}*: {{ value }}
{% endfor %}
{% endif %}
{% if evalMatches %}**Метрики:**
{% for match in evalMatches %}
- *{{ match.metric }}*: {{ match.value }}
{% endfor %}
{% endif %}
{% endif %}
{% if source == "zabbix" %}
**Статус:** {{ status }}
**Серьезность:** {{ event_severity }}
**Событие:** {{ event_name }}
**Хост:** {{ host_name }} ({{ host_ip }}:{{ host_port }})
**Тема:**
{{ alert_subject }}
**Сообщение:**
{{ alert_message }}
{% endif %}
---
*Тикет создан автоматически системой мониторинга*
Примечания:
- Шаблон поддерживает условное форматирование в зависимости от источника алерта
- Для каждого источника доступны свои переменные
- Можно создать отдельные шаблоны для каждого источника:
jira_alertmanager.tmpl,jira_grafana.tmpl,jira_zabbix.tmpl