可以在带有go模板的模板中使用模板

问题描述:

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).

使用 https://golang.org/pkg/text/template/ ,有时我需要在访问路径中使用变量(用于kubernetes部署)。 p>

我最终写的是这样的: p>

  {{if(eq .Values.cluster“ aws”}} {{.Values.redis.aws.masterHost | quote}} {{  {else}} {{.Values.redis.gcp.masterHost | quote}} {{end}} 
  code>  pre> 
 
 

我真的很想写 {{.Values.redis。{{。Values.cluster}}。masterHost | quote}} code>,它不会编译。 p>

编写类似内容的方法(因此在访问的路径中有一种变量)。 p> div>

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"