template.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package template
  13. import (
  14. "bytes"
  15. "fmt"
  16. tpl "text/template"
  17. "github.com/Masterminds/sprig/v3"
  18. corev1 "k8s.io/api/core/v1"
  19. )
  20. var tplFuncs = tpl.FuncMap{
  21. "pkcs12key": pkcs12key,
  22. "pkcs12keyPass": pkcs12keyPass,
  23. "pkcs12cert": pkcs12cert,
  24. "pkcs12certPass": pkcs12certPass,
  25. "filterPEM": filterPEM,
  26. "jwkPublicKeyPem": jwkPublicKeyPem,
  27. "jwkPrivateKeyPem": jwkPrivateKeyPem,
  28. }
  29. // So other templating calls can use the same extra functions.
  30. func FuncMap() tpl.FuncMap {
  31. return tplFuncs
  32. }
  33. const (
  34. errParse = "unable to parse template at key %s: %s"
  35. errExecute = "unable to execute template at key %s: %s"
  36. errDecodePKCS12WithPass = "unable to decode pkcs12 with password: %s"
  37. errDecodeCertWithPass = "unable to decode pkcs12 certificate with password: %s"
  38. errParsePrivKey = "unable to parse private key type"
  39. pemTypeCertificate = "CERTIFICATE"
  40. )
  41. func init() {
  42. sprigFuncs := sprig.TxtFuncMap()
  43. delete(sprigFuncs, "env")
  44. delete(sprigFuncs, "expandenv")
  45. for k, v := range sprigFuncs {
  46. tplFuncs[k] = v
  47. }
  48. }
  49. // Execute renders the secret data as template. If an error occurs processing is stopped immediately.
  50. func Execute(tpl, data map[string][]byte, secret *corev1.Secret) error {
  51. if tpl == nil {
  52. return nil
  53. }
  54. for k, v := range tpl {
  55. val, err := execute(k, string(v), data)
  56. if err != nil {
  57. return fmt.Errorf(errExecute, k, err)
  58. }
  59. secret.Data[k] = val
  60. }
  61. return nil
  62. }
  63. func execute(k, val string, data map[string][]byte) ([]byte, error) {
  64. strValData := make(map[string]string, len(data))
  65. for k := range data {
  66. strValData[k] = string(data[k])
  67. }
  68. t, err := tpl.New(k).
  69. Funcs(tplFuncs).
  70. Parse(val)
  71. if err != nil {
  72. return nil, fmt.Errorf(errParse, k, err)
  73. }
  74. buf := bytes.NewBuffer(nil)
  75. err = t.Execute(buf, strValData)
  76. if err != nil {
  77. return nil, fmt.Errorf(errExecute, k, err)
  78. }
  79. return buf.Bytes(), nil
  80. }