luet/pkg/helpers/helm.go

92 lines
2.2 KiB
Go
Raw Normal View History

2020-10-04 17:16:01 +00:00
package helpers
import (
2020-11-08 20:14:19 +00:00
"io/ioutil"
"sort"
2020-11-08 20:14:19 +00:00
"github.com/imdario/mergo"
2020-10-30 18:15:04 +00:00
"github.com/pkg/errors"
2020-11-08 20:14:19 +00:00
"gopkg.in/yaml.v2"
2020-10-04 17:16:01 +00:00
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/engine"
)
// RenderHelm renders the template string with helm
func RenderHelm(template string, values, d map[string]interface{}) (string, error) {
2020-10-04 17:16:01 +00:00
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "",
Version: "",
},
Templates: []*chart.File{
{Name: "templates", Data: []byte(template)},
},
2020-10-30 18:15:04 +00:00
Values: map[string]interface{}{"Values": values},
2020-10-04 17:16:01 +00:00
}
v, err := chartutil.CoalesceValues(c, map[string]interface{}{"Values": d})
2020-10-04 17:16:01 +00:00
if err != nil {
2020-10-30 18:15:04 +00:00
return "", errors.Wrap(err, "while rendering template")
2020-10-04 17:16:01 +00:00
}
out, err := engine.Render(c, v)
if err != nil {
2020-10-30 18:15:04 +00:00
return "", errors.Wrap(err, "while rendering template")
2020-10-04 17:16:01 +00:00
}
2020-10-30 18:15:04 +00:00
return out["templates"], nil
2020-10-04 17:16:01 +00:00
}
2020-11-08 20:14:19 +00:00
type templatedata map[string]interface{}
func UnMarshalValues(values []string) (templatedata, error) {
dst := templatedata{}
if len(values) > 0 {
allbv := values
sort.Sort(sort.Reverse(sort.StringSlice(allbv)))
for _, bv := range allbv {
current := map[string]interface{}{}
defBuild, err := ioutil.ReadFile(bv)
if err != nil {
return nil, errors.Wrap(err, "rendering file "+bv)
}
err = yaml.Unmarshal(defBuild, &current)
if err != nil {
return nil, errors.Wrap(err, "rendering file "+bv)
}
if err := mergo.Merge(&dst, current); err != nil {
return nil, errors.Wrap(err, "merging values file "+bv)
}
}
}
return dst, nil
}
func RenderFiles(toTemplate, valuesFile string, defaultFile ...string) (string, error) {
2020-11-08 20:14:19 +00:00
raw, err := ioutil.ReadFile(toTemplate)
if err != nil {
return "", errors.Wrap(err, "reading file "+toTemplate)
}
if !Exists(valuesFile) {
return "", errors.Wrap(err, "file not existing "+valuesFile)
}
val, err := ioutil.ReadFile(valuesFile)
2020-11-08 20:14:19 +00:00
if err != nil {
return "", errors.Wrap(err, "reading file "+valuesFile)
}
var values templatedata
if err = yaml.Unmarshal(val, &values); err != nil {
2020-11-08 20:14:19 +00:00
return "", errors.Wrap(err, "unmarshalling file "+toTemplate)
}
dst, err := UnMarshalValues(defaultFile)
if err != nil {
return "", errors.Wrap(err, "unmarshalling values")
}
return RenderHelm(string(raw), values, dst)
2020-11-08 20:14:19 +00:00
}