1

我想要一个检查所有“必需”变量的文件。到目前为止,我想出了这个,但看起来这不是“最佳”实践

值.yaml

# this is required name of the hosted zone
domainZone: "" 
someOtherRequireVar: ""

/templates/required.yaml

# the block below makes sure that our required variables are 
# declared in the values file and if not that will throw the error
# so even the block below is commeted, it's still evaluated by the HELM and error
# will be generated if the variable's value is not set
# {{ .Values.domainZone | required "Domain Zone is required and should be non-empty string" }}
# {{ .Values.someOtherRequireVar | required "The someOtherRequireVar is also required and should be non-empty string" }}

有没有更好的方法来实现这一目标?

4

1 回答 1

1

我建议使用命名模板进行验证,您可以在安装说明中执行,而不是常规模板文件。此外,通过对单个值使用故障安全验证函数(与 不同require),您可以在helm命令执行失败之前验证多个值。

Bitnami 图表使用这种策略。

设置

部分文件中,例如templates/_helpers.tpl,定义命名模板以验证提供的值:

{{/* Compile all validation warnings into a single message and call fail. */}}
{{- define "mychart.validateValues" -}}
{{- $messages := list -}}
{{- $messages = append $messages (include "mychart.validateValues.foo" .) -}}
{{- $messages = append $messages (include "mychart.validateValues.bar" .) -}}
{{- $messages = without $messages "" -}}
{{- $message := join "\n" $messages -}}

{{- if $message -}}
{{- printf "\nVALUES VALIDATION:\n%s" $message | fail -}}
{{- end -}}
{{- end -}}

{{/* Validate value of foo */}}
{{- define "mychart.validateValues.foo" -}}
{{- if not (and .Values.foo (kindIs "string" .Values.foo)) -}}
mychart: foo
    `foo` is required and should be a non-empty string
{{- end -}}
{{- end -}}

{{/* Validate the value of bar */}}
{{- define "mychart.validateValues.bar" -}}
{{- if not (and .Values.bar (kindIs "string" .Values.bar)) -}}
mychart: bar
    `bar` is required and should be a non-empty string
{{- end -}}
{{- end -}}

在这种情况下,命名模板mychart.validateValues将运行多个验证(即mychart.validateValues.foomychart.validateValues.bar。如果一个或多个验证产生验证警告,它将调用fail警告摘要。

templates/NOTES.txt中,评估命名模板以进行验证:

{{- include "mychart.validateValues" . }}

测试

使用以下values.yaml文件:

bar: 24

模板化、安装或升级图表将失败并显示以下消息:

Error: execution error at (test/templates/NOTES.txt:1:4): 
VALUES VALIDATION:
mychart: foo
    `foo` is required and should be a non-empty string
mychart: bar
    `bar` is required and should be a non-empty string
于 2021-10-29T02:21:17.360 回答