doukanwa6872 2018-11-16 15:09
浏览 26
已采纳

可以在带有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).

  • 写回答

1条回答 默认 最新

  • du0531 2018-11-23 12:39
    关注

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?