Skip to content

Commit

Permalink
Support jinja2 template in alertmanager_labels
Browse files Browse the repository at this point in the history
  • Loading branch information
tgxworld committed Mar 6, 2025
1 parent 55ccb06 commit 909faaa
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
8 changes: 8 additions & 0 deletions elastalert/alerters/alertmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from datetime import datetime, timedelta, timezone
import requests
from jinja2 import Template
from requests import RequestException
from requests.auth import HTTPBasicAuth

Expand Down Expand Up @@ -48,12 +49,19 @@ def alert(self, matches):
proxies = {'https': self.proxies} if self.proxies else None
auth = HTTPBasicAuth(self.alertmanager_basic_auth_login, self.alertmanager_basic_auth_password) if self.alertmanager_basic_auth_login else None

resolved_labels = {}
for key, template_str in self.labels.items():
jinja_template = Template(template_str)
resolved_labels[key] = jinja_template.render(matches[0] | {self.rule['jinja_root_name']: matches[0]})

self.labels.update({
label: self._json_or_string(lookup_es_key(matches[0], term))
for label, term in self.fields.items()})

self.labels.update(
alertname=self.alertname,
elastalert_rule=self.rule.get('name'))

self.annotations.update({
self.title_labelname: self.create_title(matches),
self.body_labelname: self.create_alert_body(matches)})
Expand Down
44 changes: 44 additions & 0 deletions tests/alerters/alertmanager_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,3 +450,47 @@ def test_alertmanager_resolve_timeout(caplog):
)
assert expected_data == json.loads(mock_post_request.call_args_list[0][1]['data'])
assert ('elastalert', logging.INFO, "Alert sent to Alertmanager") == caplog.record_tuples[0]

def test_alertmanager_labels_with_jinja2():
rule = {
'name': 'Test Alertmanager Rule',
'type': 'any',
'alertmanager_hosts': ['http://alertmanager:9093'],
'alertmanager_alertname': 'Title',
'alertmanager_annotations': {'severity': 'error'},
'alertmanager_labels': {
'source': 'elastalert',
'service_name': '{{ service.name }}',
'environment': '{{ env.name }}',
'region': '{{ env.region }}',
'host': '{{ _data["host"] }}',
},
'alertmanager_fields': {'msg': 'message', 'log': '@log_name'},
'alert_subject_args': ['message', '@log_name'],
'alert': []
}

rules_loader = FileRulesLoader({})
rules_loader.load_modules(rule)
alert = AlertmanagerAlerter(rule)

match = {
'service': {'name': 'my-service'},
'env': {'name': 'production', 'region': 'us-east-1'},
'host': 'server01.example.com',
}

with mock.patch('requests.post') as mock_post_request:
alert.alert([match])

expected_labels = {
'service_name': 'my-service',
'environment': 'production',
'region': 'us-east-1',
'host': 'server01.example.com',
'alertname': 'Test Alertmanager Rule',
'elastalert_rule': 'Test Alertmanager Rule',
}

payload = json.loads(mock_post_request.call_args[1]['data'])[0]
assert payload['labels'] == expected_labels

0 comments on commit 909faaa

Please sign in to comment.