-
Notifications
You must be signed in to change notification settings - Fork 584
/
templates.go
76 lines (69 loc) · 2.33 KB
/
templates.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package templates
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/blang/semver"
"github.com/ghodss/yaml"
"github.com/rancher/kontainer-driver-metadata/rke/templates"
"github.com/rancher/norman/types/convert"
"github.com/rancher/rke/metadata"
"github.com/sirupsen/logrus"
)
func CompileTemplateFromMap(tmplt string, configMap interface{}) (string, error) {
out := new(bytes.Buffer)
templateFuncMap := sprig.TxtFuncMap()
templateFuncMap["GetKubednsStubDomains"] = GetKubednsStubDomains
templateFuncMap["toYaml"] = ToYAML
t := template.Must(template.New("compiled_template").Funcs(templateFuncMap).Parse(tmplt))
if err := t.Execute(out, configMap); err != nil {
return "", err
}
return out.String(), nil
}
func GetVersionedTemplates(templateName string, data map[string]interface{}, k8sVersion string) (string, error) {
if template, ok := data[templateName]; ok {
return convert.ToString(template), nil
}
return getTemplate(templateName, k8sVersion)
}
func GetKubednsStubDomains(stubDomains map[string][]string) string {
json, _ := json.Marshal(stubDomains)
return string(json)
}
func ToYAML(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
// Swallow errors inside of a template so it doesn't affect remaining template lines
logrus.Errorf("[ToYAML] Error marshaling %v: %v", v, err)
return ""
}
yamlData, err := yaml.JSONToYAML(data)
if err != nil {
// Swallow errors inside of a template so it doesn't affect remaining template lines
logrus.Errorf("[ToYAML] Error converting json to yaml for %v: %v ", string(data), err)
return ""
}
return strings.TrimSuffix(string(yamlData), "\n")
}
func getTemplate(templateName, k8sVersion string) (string, error) {
versionData := metadata.K8sVersionToTemplates[templateName]
toMatch, err := semver.Make(k8sVersion[1:])
if err != nil {
return "", fmt.Errorf("k8sVersion not sem-ver %s %v", k8sVersion, err)
}
for k := range versionData {
testRange, err := semver.ParseRange(k)
if err != nil {
logrus.Errorf("range for %s not sem-ver %v %v", templateName, testRange, err)
continue
}
if testRange(toMatch) {
return metadata.K8sVersionToTemplates[templates.TemplateKeys][versionData[k]], nil
}
}
return "", fmt.Errorf("no %s template found for k8sVersion %s", templateName, k8sVersion)
}