Is it possible to use a template inside a template with go template

11/16/2018

Using https://golang.org/pkg/text/template/, I sometimes need to use variables in the accessed path (for kubernetes deployments).

I end up writing something like :

{{ if (eq .Values.cluster "aws" }}{{ .Values.redis.aws.masterHost | quote }}{{else}}{{ .Values.redis.gcp.masterHost | quote }}{{end}}

What I'd really like to write is pretty much {{ .Values.redis.{{.Values.cluster}}.masterHost | quote }} , which doesn't compile.

Is there a way to write something similar ? (so having a kind of variable in the accessed path).

-- C4stor
go
kubernetes-helm

1 Answer

11/23/2018

You can use _helpers.tpl file to define logic and operate with values.

_helpers.tpl

{{/*
Get redis host based on cluster.
*/}}
{{- define "chart.getRedis" -}}
{{- if eq .Values.cluster "aws" -}}
{{- .Values.redis.aws.masterHost | quote -}}
{{- else -}}
{{- .Values.redis.gcp.masterHost | quote -}}
{{- end -}}
{{- end -}}

values.yaml

cluster: local
redis:
  aws:
    masterHost: "my-aws-host"
  gcp:
    masterHost: "my-gcp-host"

And use it in your Deployment (here's a ConfigMap example to keep it shorter)

configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: Configmap
data:
  redis: {{ template "chart.getRedis" . }}

Output:

helm install --dry-run --debug mychart

[debug] Created tunnel using local port: '64712'

...

COMPUTED VALUES:
cluster: local
redis:
  aws:
    masterHost: my-aws-host
  gcp:
    masterHost: my-gcp-host

HOOKS:
MANIFEST:

---
# Source: mychart/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: Configmap
data:
  redis: "my-gcp-host"

Set cluster value to aws:

helm install --dry-run --debug mychart --set-string=cluster=aws

[debug] Created tunnel using local port: '64712'

...

COMPUTED VALUES:
cluster: local
redis:
  aws:
    masterHost: my-aws-host
  gcp:
    masterHost: my-gcp-host

HOOKS:
MANIFEST:

---
# Source: mychart/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: Configmap
data:
  redis: "my-aws-host"
-- edbighead
Source: StackOverflow