feat(processors.template): Add sprig function for templates (#16497)

Co-authored-by: Pieter Slabbert <pieter.slabbert@ilovezoona.com>
This commit is contained in:
Pieter Slabbert 2025-02-14 00:45:44 +02:00 committed by GitHub
parent 1915a0a49e
commit 9a43d7c35e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 41 additions and 2 deletions

View File

@ -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][].

View File

@ -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)
}

View File

@ -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)
}