Skip to content

Commit

Permalink
Jinja 3.0.1, alert_text_jinja tests, fix #310
Browse files Browse the repository at this point in the history
  • Loading branch information
mrfroggg committed Jun 30, 2021
1 parent 975619c commit b4b0c2a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
6 changes: 3 additions & 3 deletions elastalert/alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ def _add_custom_alert_text(self):
# Top fields are accessible via `{{field_name}}` or `{{jinja_root_name['field_name']}}`
# `jinja_root_name` dict is useful when accessing *fields with dots in their keys*,
# as Jinja treat dot as a nested field.
alert_text = self.rule.get("jinja_template").render(**{**self.rule, **self.match},
**{self.rule['jinja_root_name']: {**self.rule,
**self.match}})
template_values = self.rule | self.match
alert_text = self.rule.get("jinja_template").render(
template_values | {self.rule['jinja_root_name']: template_values})
elif 'alert_text_args' in self.rule:
alert_text_args = self.rule.get('alert_text_args')
alert_text_values = [lookup_es_key(self.match, arg) for arg in alert_text_args]
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ croniter>=0.3.16
elasticsearch==7.0.0
envparse>=0.2.0
exotel>=0.1.3
Jinja2==2.11.3
Jinja2==3.0.1
jira>=2.0.0
jsonschema>=3.0.2
prison>=0.1.2
Expand Down
28 changes: 27 additions & 1 deletion tests/alerts_test.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
import datetime
import json

from unittest import mock
from jinja2 import Template

from elastalert.alerts import Alerter
from elastalert.alerts import BasicMatchString
Expand Down Expand Up @@ -157,6 +157,32 @@ def test_alert_text_kw_global_substitution(ea):
assert 'Abc: abc from match' in alert_text


def test_alert_text_jinja(ea):
rule = ea.rules[0].copy()
rule['foo_rule'] = 'foo from rule'
rule['owner'] = 'the owner from rule'
rule['abc'] = 'abc from rule'
rule['alert_text'] = 'Owner: {{owner}}; Foo: {{_data["foo_rule"]}}; Abc: {{abc}}; Xyz: {{_data["xyz"]}}'
rule['alert_text_type'] = "alert_text_jinja"
rule['jinja_root_name'] = "_data"
rule['jinja_template'] = Template(str(rule['alert_text']))

match = {
'@timestamp': '2016-01-01',
'field': 'field_value',
'abc': 'abc from match',
'xyz': 'from match'
}

alert_text = str(BasicMatchString(rule, match))
assert 'Owner: the owner from rule' in alert_text
assert 'Foo: foo from rule' in alert_text
assert 'Xyz: from match' in alert_text

# When the key exists in both places, it will come from the match
assert 'Abc: abc from match' in alert_text


def test_resolving_rule_references():
rule = {
'name': 'test_rule',
Expand Down

0 comments on commit b4b0c2a

Please sign in to comment.