代码之家  ›  专栏  ›  技术社区  ›  C4stor

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

  •  0
  • C4stor  · 技术社区  · 6 年前

    使用 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 }} ,但无法编译。

    有没有写类似的东西的方法?(所以在访问路径中有一种变量)。

    1 回复  |  直到 6 年前
        1
  •  1
  •   edbighead    6 年前

    你可以使用 _helpers.tpl 用于定义逻辑和使用值进行操作的文件。

    _助手.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 -}}
    

    价值观

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

    在您的部署中使用它(下面是一个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"