diff --git a/plugins/processors/template/README.md b/plugins/processors/template/README.md index 9893fbf63..35c940e62 100644 --- a/plugins/processors/template/README.md +++ b/plugins/processors/template/README.md @@ -7,6 +7,7 @@ routing option. The template has access to each metric's measurement name, tags, fields, and timestamp using the [interface in `/template_metric.go`](template_metric.go). +[Sprig](http://masterminds.github.io/sprig/) helper functions are available. Read the full [Go Template Documentation][]. diff --git a/plugins/processors/template/template.go b/plugins/processors/template/template.go index 8251fe803..4ae8b0af4 100644 --- a/plugins/processors/template/template.go +++ b/plugins/processors/template/template.go @@ -7,6 +7,7 @@ import ( "strings" "text/template" + "github.com/Masterminds/sprig/v3" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/processors" ) @@ -64,12 +65,12 @@ func (r *TemplateProcessor) Apply(in ...telegraf.Metric) []telegraf.Metric { func (r *TemplateProcessor) Init() error { var err error - r.tmplTag, err = template.New("tag template").Parse(r.Tag) + r.tmplTag, err = template.New("tag template").Funcs(sprig.TxtFuncMap()).Parse(r.Tag) if err != nil { return fmt.Errorf("creating tag name template failed: %w", err) } - r.tmplValue, err = template.New("value template").Parse(r.Template) + r.tmplValue, err = template.New("value template").Funcs(sprig.TxtFuncMap()).Parse(r.Template) if err != nil { return fmt.Errorf("creating value template failed: %w", err) } diff --git a/plugins/processors/template/template_test.go b/plugins/processors/template/template_test.go index b8a3be5b7..cc29e9e1d 100644 --- a/plugins/processors/template/template_test.go +++ b/plugins/processors/template/template_test.go @@ -305,3 +305,40 @@ func TestTracking(t *testing.T) { return len(delivered) == 1 }, time.Second, 100*time.Millisecond, "%d delivered but 1 expected", len(delivered)) } + +func TestSprig(t *testing.T) { + plugin := TemplateProcessor{ + Tag: `{{ .Tag "foo" | lower }}`, + Template: `{{ .Name | upper }}`, + } + + err := plugin.Init() + require.NoError(t, err) + + input := []telegraf.Metric{ + testutil.MustMetric( + "cpu", + map[string]string{"foo": "MEASUREMENT"}, + map[string]interface{}{ + "time_idle": 42, + }, + time.Unix(0, 0), + ), + } + + actual := plugin.Apply(input...) + expected := []telegraf.Metric{ + testutil.MustMetric( + "cpu", + map[string]string{ + "foo": "MEASUREMENT", + "measurement": "CPU", + }, + map[string]interface{}{ + "time_idle": 42, + }, + time.Unix(0, 0), + ), + } + testutil.RequireMetricsEqual(t, expected, actual) +}