kudobuilder / kudo

Kubernetes Universal Declarative Operator (KUDO)
https://kudo.dev
Apache License 2.0
1.17k stars 103 forks source link

Support for _helper.tpl so Go templates can be shared by all files in templates directory #1774

Open andylholloway opened 3 years ago

andylholloway commented 3 years ago

Hi We have quite a bit of repetition in our templates. To try and reduce this repetition I have been looking at using the Go template function Kudo supports.

I have been able to define and use templates within the same template file e.g.

{{- define "creatorLabel" -}}
  creator: alh
{{- end -}}

{{- define "apiVersionLabel" -}}
  app-version: "{{ .AppVersion }}"
{{- end -}}

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Name }}-echoserver-deployment
  labels:
    {{ template "creatorLabel" }}
    {{ template "apiVersionLabel" . }}
spec:
  selector:
    matchLabels:
      app: {{ .Name }}-echoserver
  replicas: {{ .Params.replicas }}
  template:
    metadata:
      labels:
        app: {{ .Name }}-echoserver
        {{ template "creatorLabel" }}
        {{ template "apiVersionLabel" . }}
    spec:
      containers:
        - name: echoserver
          image: k8s.gcr.io/echoserver:1.4
          ports:
            - containerPort: 8080

This helps to reduce some of the repetition within the same template, but ideally I would be able to move the template definitions into a file which can be shared by all template files in the /templates directory in the same way helm uses _helper.tpl.

I have looked through the documentation but I can't see how to create and reference a "helper" file. I have tried referencing the a template in multiple yaml files, but I get an error saying: "... at <{{template "creatorLabel"}}>: template "creatorLabel" not defined".

Is it be possible to create an external template / helper file?