Skip to content

Commit e385e11

Browse files
zan-xhipePieter Slabbert
authored andcommitted
feat(processors.template): Add sprig function for templates (influxdata#16497)
Co-authored-by: Pieter Slabbert <pieter.slabbert@ilovezoona.com>
1 parent 86d1ea8 commit e385e11

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

plugins/processors/template/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ routing option.
77

88
The template has access to each metric's measurement name, tags, fields, and
99
timestamp using the [interface in `/template_metric.go`](template_metric.go).
10+
[Sprig](http://masterminds.github.io/sprig/) helper functions are available.
1011

1112
Read the full [Go Template Documentation][].
1213

plugins/processors/template/template.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"strings"
88
"text/template"
99

10+
"github.com/Masterminds/sprig/v3"
1011
"github.com/influxdata/telegraf"
1112
"github.com/influxdata/telegraf/plugins/processors"
1213
)
@@ -64,12 +65,12 @@ func (r *TemplateProcessor) Apply(in ...telegraf.Metric) []telegraf.Metric {
6465
func (r *TemplateProcessor) Init() error {
6566
var err error
6667

67-
r.tmplTag, err = template.New("tag template").Parse(r.Tag)
68+
r.tmplTag, err = template.New("tag template").Funcs(sprig.TxtFuncMap()).Parse(r.Tag)
6869
if err != nil {
6970
return fmt.Errorf("creating tag name template failed: %w", err)
7071
}
7172

72-
r.tmplValue, err = template.New("value template").Parse(r.Template)
73+
r.tmplValue, err = template.New("value template").Funcs(sprig.TxtFuncMap()).Parse(r.Template)
7374
if err != nil {
7475
return fmt.Errorf("creating value template failed: %w", err)
7576
}

plugins/processors/template/template_test.go

+37
Original file line numberDiff line numberDiff line change
@@ -305,3 +305,40 @@ func TestTracking(t *testing.T) {
305305
return len(delivered) == 1
306306
}, time.Second, 100*time.Millisecond, "%d delivered but 1 expected", len(delivered))
307307
}
308+
309+
func TestSprig(t *testing.T) {
310+
plugin := TemplateProcessor{
311+
Tag: `{{ .Tag "foo" | lower }}`,
312+
Template: `{{ .Name | upper }}`,
313+
}
314+
315+
err := plugin.Init()
316+
require.NoError(t, err)
317+
318+
input := []telegraf.Metric{
319+
testutil.MustMetric(
320+
"cpu",
321+
map[string]string{"foo": "MEASUREMENT"},
322+
map[string]interface{}{
323+
"time_idle": 42,
324+
},
325+
time.Unix(0, 0),
326+
),
327+
}
328+
329+
actual := plugin.Apply(input...)
330+
expected := []telegraf.Metric{
331+
testutil.MustMetric(
332+
"cpu",
333+
map[string]string{
334+
"foo": "MEASUREMENT",
335+
"measurement": "CPU",
336+
},
337+
map[string]interface{}{
338+
"time_idle": 42,
339+
},
340+
time.Unix(0, 0),
341+
),
342+
}
343+
testutil.RequireMetricsEqual(t, expected, actual)
344+
}

0 commit comments

Comments
 (0)