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

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

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

我最后写的是:

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

我真正想写的几乎是 {{ .Values.redis.{{.Values.cluster}}.masterHost | quote }} ,它无法编译。

有没有办法写类似的东西? (因此在访问路径中有一种变量)。

您可以使用 _helpers.tpl 文件来定义逻辑和操作值。

_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"

并在您的 Deployment 中使用它(这里有一个 ConfigMap 示例以使其更短)

configmap.yaml

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

输出:

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"

将集群值设置为 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"