可以在模板中使用带有go模板的模板 [英] Is it possible to use a template inside a template with go template

查看:209
本文介绍了可以在模板中使用带有go模板的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我最终写的是这样的:

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

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

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

推荐答案

您可以使用

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"

并在部署中使用它(这里是一个ConfigMap示例,以使其更短)

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" . }}

输出:

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"

这篇关于可以在模板中使用带有go模板的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆