Skip to content

Commit

Permalink
Adds match and stringSlice to template functions (prometheus-communit…
Browse files Browse the repository at this point in the history
…y#55)

This commit ports template functions added to alertmanager in
prometheus/alertmanager#1452 and prometheus/alertmanager#2101 and brings
jiralert up to date (without safeHtml) with the alertmanger code in
https://github.com/prometheus/alertmanager/blob/0c0c6bdb0133e399c1a9fe4c1a170ce49ec67b58/template/template.go#L127-L147

The `match` function allows for prometheus like substring matching for
more complex templates.

The `stringSlice` function renders a `string` into a `[]string` that is
suitable for use with `Remove`.

My original use case that led to this patch was this template:

```yaml
receivers:
- name: jira
  summary: '{{ if .CommonLabels.jira_summary }}{{ .CommonLabels.jira_summary }}{{
    else }}{{ .GroupLabels.SortedPairs.Values | join " " }}{{ end }}'
```

I thought, 'wouldn't it be nice to remove the name of the jira project
from the title of the issue?', so I tried this template:

```yaml
receivers:
- name: jira
  summary: '{{ if .CommonLabels.jira_summary }}{{ .CommonLabels.jira_summary }}{{
    else }}{{ .GroupLabels.Remove "jira_project" }}{ .SortedPairs.Values | join " " }}{{ end }}'
```

This failed with:

```
err="template: :1:105: executing \"\" at <\"jira_project\">: can't
handle \"jira_project\" for arg of type []string" receiver=jira
groupLabels="unsupported value type"
```

After some research, I found prometheus/alertmanager#2101, with the
description:

> Since it's impossible to create a string slice in a Go template by
> default, add a function to work around this problem.

With this patch, we should be able to pass a string directly to the
template Remove function, as alertmanager does.

Signed-off-by: Greg Burek <[email protected]>

Co-authored-by: Alin Sinpalean <[email protected]>
  • Loading branch information
gburek-fastly and free authored May 14, 2020
1 parent f7b8dc2 commit 11f1d7d
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pkg/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,14 @@ var funcs = template.FuncMap{
"join": func(sep string, s []string) string {
return strings.Join(s, sep)
},
"match": regexp.MatchString,
"reReplaceAll": func(pattern, repl, text string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, repl)
},
"stringSlice": func(s ...string) []string {
return s
},
}

// LoadTemplate reads and parses all templates defined in the given file and constructs a jiralert.Template.
Expand Down

0 comments on commit 11f1d7d

Please sign in to comment.