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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)