【问题标题】:If condition checking value returned by helm template如果 helm 模板返回条件检查值
【发布时间】:2020-07-23 12:25:21
【问题描述】:

我有一个包含 2 个子图表的父图表。父图表有 global.myflag,而子图表有 myflag 字段,在它们各自的 values.yaml 中。我想要灵活性,子图表可以独立部署。因此,我在要检查的子图表 _helper.tpl 中添加了一个模板函数 - 如果 global.myflag 存在,则使用该值 - 否则使用子图表中 myflag 的值

模板将返回真/假。像这样 -

{{- define "isFlagEnabled" -}}
{{- $flag := false -}}
{{- if .Values.myflag -}}
{{- $flag := .Values.myflag -}}
{{- end -}}
{{- if .Values.global.myflag -}}
{{- $flag := .Values.global.myflag -}}
{{- end -}}
{{- printf "%s" $flag -}}
{{- end -}}

使用这个值(真/假),我想在我的 config.yaml 中设置一些值。

{{- if eq (value from template) true -}}

我在这里有两个问题 - 1.我们可以对模板值做'if'条件吗?如何? 2. 有更好的方法吗?

【问题讨论】:

    标签: kubernetes-helm


    【解决方案1】:

    isFlagEnabled 模板的定义

    修饰和清理你的函数

    {{- define "isFlagEnabled" -}}
    {{- if .Values.global -}} {{/* <-- check parent exists to avoid nil pointer evaluating interface {}.myflag */}}
    {{- if .Values.global.myflag -}}
    {{- .Values.global.myflag -}}
    {{- end -}}
    {{- else if .Values.myflag -}} {{/* <-- make sure its else if so you wont override if both defined */}}
    {{- .Values.myflag -}}
    {{- else -}}
    {{- printf "false" }}
    {{- end -}}
    {{- end -}}
    

    使用模板

    在另一个模板中

    在 golang 模板语法中使用模板时,您需要用圆括号对其进行转义:

    {{- define "flagUsage" -}}
    {{- if eq (include "isFlagEnabled" .) "true" -}}
    {{- printf "%s" (include "isFlagEnabled" .) -}}
    {{- end -}}
    {{- end -}}
    

    另一个在资源中使用的例子

    注意该模板在示例中被使用了两次,一次作为 if 运算符的操作数,一次作为标签的文本

    {{- if eq (include "isFlagEnabled" .) "true" -}} {{/* <--- operand used in spring function surrounded by `{{ }}` */}}
    apiVersion: v1
    kind: Service
    metadata:
        name: {{ include "my-chart.fullname" . }}
        labels:
            my-meta-label: {{ include "isFlagEnabled" . }} {{/* <---- plain text */}}
    spec:
        type: {{ .Values.service.type }}
        ports:
            - port: {{ .Values.service.port }}
            targetPort: http
            protocol: TCP
            name: http
        selector:
            {{- include "my-chart.selectorLabels" . | nindent 4 }}
    {{- end }}
    

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2018-06-03
      • 2019-02-13
      • 2021-12-07
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      相关资源
      最近更新 更多