diff --git a/docs/configuration/template_reference.md b/docs/configuration/template_reference.md index 34557ecd83..5c96ee597b 100644 --- a/docs/configuration/template_reference.md +++ b/docs/configuration/template_reference.md @@ -76,6 +76,7 @@ versions. | graphLink | expr | string | Returns path to graph view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. | | tableLink | expr | string | Returns path to tabular ("Table") view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. | | parseDuration | string | float | Parses a duration string such as "1h" into the number of seconds it represents. | +| stripDomain | string | string | Removes the domain part of a FQDN. Leaves port untouched. | ### Others diff --git a/template/template.go b/template/template.go index 6962639986..4058ad3ae5 100644 --- a/template/template.go +++ b/template/template.go @@ -196,6 +196,21 @@ func NewTemplateExpander( } return host }, + "stripDomain": func(hostPort string) string { + host, port, err := net.SplitHostPort(hostPort) + if err != nil { + host = hostPort + } + ip := net.ParseIP(host) + if ip != nil { + return hostPort + } + host = strings.Split(host, ".")[0] + if port != "" { + return net.JoinHostPort(host, port) + } + return host + }, "humanize": func(i interface{}) (string, error) { v, err := convertToFloat(i) if err != nil { diff --git a/template/template_test.go b/template/template_test.go index 342a951122..45d1a66e74 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -480,6 +480,41 @@ func TestTemplateExpansion(t *testing.T) { text: "{{ printf \"%0.2f\" (parseDuration \"1h2m10ms\") }}", output: "3720.01", }, + { + // Simple hostname. + text: "{{ \"foo.example.com\" | stripDomain }}", + output: "foo", + }, + { + // Hostname with port. + text: "{{ \"foo.example.com:12345\" | stripDomain }}", + output: "foo:12345", + }, + { + // Simple IPv4 address. + text: "{{ \"192.0.2.1\" | stripDomain }}", + output: "192.0.2.1", + }, + { + // IPv4 address with port. + text: "{{ \"192.0.2.1:12345\" | stripDomain }}", + output: "192.0.2.1:12345", + }, + { + // Simple IPv6 address. + text: "{{ \"2001:0DB8::1\" | stripDomain }}", + output: "2001:0DB8::1", + }, + { + // IPv6 address with port. + text: "{{ \"[2001:0DB8::1]:12345\" | stripDomain }}", + output: "[2001:0DB8::1]:12345", + }, + { + // Value can't be split into host and port. + text: "{{ \"[2001:0DB8::1]::12345\" | stripDomain }}", + output: "[2001:0DB8::1]::12345", + }, }) }