Skip to content

Commit

Permalink
feat: Add template functions for proper YAML escaping and quoting
Browse files Browse the repository at this point in the history
  • Loading branch information
pcfreak30 committed Dec 28, 2024
1 parent 36e2d9a commit fa897a2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
15 changes: 13 additions & 2 deletions cmd/promster/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"context"
"encoding/json"
"fmt"
"go.lumeweb.com/etcd-registry/types"
"sort"
"io"
"net/http"
"os"
"os/signal"
"reflect"
"sort"
"strings"
"sync"
"text/template"
Expand Down Expand Up @@ -67,6 +68,16 @@ func (sg *ServiceGroup) Validate() error {
return nil
}

var templateFuncs = template.FuncMap{
"quote": func(v interface{}) string {
return fmt.Sprintf("%q", v)
},
"toJson": func(v interface{}) string {
b, _ := json.Marshal(v)
return string(b)
},
}

func executeTemplate(data interface{}) (string, error) {
// Validate service groups before template execution
config, ok := data.(PrometheusConfig)
Expand All @@ -77,7 +88,7 @@ func executeTemplate(data interface{}) (string, error) {
}
}
}
tmpl, err := template.New(PROM_TEMPLATE_FILE).Parse(prometheusTemplate)
tmpl, err := template.New(PROM_TEMPLATE_FILE).Funcs(templateFuncs).Parse(prometheusTemplate)
if err != nil {
return "", err
}
Expand Down
18 changes: 9 additions & 9 deletions cmd/promster/prometheus.yml.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,27 @@ scrape_configs:
- targets: ['localhost:9090']
{{ if .AdminPassword }}
basic_auth:
username: "{{.AdminUsername}}"
password: "{{.AdminPassword}}"
username: {{.AdminUsername | quote}}
password: {{.AdminPassword | quote}}
{{ end }}

{{- if .ServiceGroups }}
{{- range .ServiceGroups }}
- job_name: '{{ .Name }}'
scheme: "{{$.Scheme}}"
- job_name: {{.Name | quote}}
scheme: {{$.Scheme | quote}}
tls_config:
insecure_skip_verify: {{if eq $.TlsInsecure "true"}}true{{else}}false{{end}}
static_configs:
- targets: {{ .Targets }}
- targets: {{.Targets | toJson}}
labels:
{{- range $key, $value := .Labels }}
{{ $key }}: "{{ $value }}"
{{$key}}: {{$value | quote}}
{{- end }}
{{ if .BasicAuth }}
basic_auth:
username: "{{ .BasicAuth.Username }}"
password: "{{ .BasicAuth.Password }}"
username: {{.BasicAuth.Username | quote}}
password: {{.BasicAuth.Password | quote}}
{{ end }}
metrics_path: "{{ .MetricsPath }}"
metrics_path: {{.MetricsPath | quote}}
{{- end }}
{{- end }}

0 comments on commit fa897a2

Please sign in to comment.