helm-import/internal/exporters/secret.go

75 lines
2.8 KiB
Go
Executable File

package exporters
import (
"encoding/json"
"regexp"
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/yaml"
)
// Secret removes basic stuff like namespace, status, managedBy and lastAppliedConfiguration
func Secret(secret *v1.Secret, jqcommands []string, nobuiltinmods bool, chartname string, lessOpinions bool) string {
if !nobuiltinmods {
// All the below do not belong in a helm chart yaml
delete(secret.ObjectMeta.Annotations, "kubectl.kubernetes.io/last-applied-configuration")
delete(secret.ObjectMeta.Annotations, "deployment.kubernetes.io/revision")
secret.ObjectMeta.ManagedFields = nil
secret.ObjectMeta.Namespace = ""
secret.ObjectMeta.ResourceVersion = ""
secret.ObjectMeta.Generation = 0
secret.ObjectMeta.SelfLink = ""
secret.ObjectMeta.UID = ""
jqcommands = append(jqcommands, "del(.metadata.creationTimestamp)")
// Here's where we get more opinionated though
if !lessOpinions {
jqcommands = append(jqcommands, ".metadata.name = \"{{ $fullName }}\"")
jqcommands = append(jqcommands, ".metadata.labels += {HELMTEMPLATEDELETEKEY: \"{{- include \\\""+chartname+".labels\\\" . | nindent 4 }}\"}")
jqcommands = append(jqcommands, ".metadata.annotations += {HELMTEMPLATEDELETEKEY: \"{{- include \\\""+chartname+".annotations\\\" . | nindent 4 }}\"}")
jqcommands = append(jqcommands, ".data += { \"HELMTEMPLATEDELETEKEY0\": \"{{- range $key, $value := .Values."+chartname+".secretenv }}\" }")
jqcommands = append(jqcommands, ".data += { \"HELMTEMPLATEDELETEKEY1\": \"{{ $key }}: {{ $value | quote }}\" }")
jqcommands = append(jqcommands, ".data += { \"HELMTEMPLATEDELETEKEY2\": \"{{- end }}\" }")
}
}
// Jump to json for jq ;-)
jsonForm, err := json.Marshal(secret)
if err != nil {
panic(err.Error())
}
var intermediateJSONForm []byte
var finalJSONForm []byte
if len(jqcommands) > 0 {
for _, command := range jqcommands {
intermediateJSONForm = jQOnJSONByteArray(command, jsonForm)
jsonForm = intermediateJSONForm
}
finalJSONForm = jsonForm
} else {
finalJSONForm = jsonForm
}
y, err := yaml.JSONToYAML(finalJSONForm)
if err != nil {
panic(err.Error())
}
ret := "{{- $fullName := include \"" + chartname + ".fullname\" . -}}\n"
ret += "kind: Secret\n"
ret += "apiVersion: v1\n"
out := string(y)
var re = regexp.MustCompile(`HELMTEMPLATEDELETEKEY: '([^']*)'`)
out = re.ReplaceAllString(out, "$1")
re = regexp.MustCompile(`HELMTEMPLATEDELETEKEY0: '([^']*)'`)
out = re.ReplaceAllString(out, "$1")
re = regexp.MustCompile(`HELMTEMPLATEDELETEKEY1: '([^']*)'`)
out = re.ReplaceAllString(out, "$1")
re = regexp.MustCompile(`HELMTEMPLATEDELETEKEY2: '([^']*)'`)
out = re.ReplaceAllString(out, "$1")
re = regexp.MustCompile(`(?s)- HELMTEMPLATEDELETEKEYANDARRAYMARKER: '([^']*)'`)
out = re.ReplaceAllString(out, "$1")
ret += string(out)
return ret
}