我现在正在这样做:
value: {{ required "A valid .Values.foo entry required!" .Values.foo }}
但是要为模板中的所有必需值提供相同的消息很麻烦,并且使模板混乱。
有没有更好的方法可以在模板\之外定义它?还是有一种更干净的方法可以在模板本身内进行定义?
答案 0 :(得分:1)
要将缺失项的名称显示为必需的文本,您可以执行以下操作:
{{- range $field, $my_key := $data }}
{{- if hasKey $dic1 $my_key }}
{{ $field }}: {{ index $dic1 $my_key | b64enc}}
{{- else if hasKey $dic2 $my_key }}
{{ $field }}: {{ index $dic2 $my_key | b64enc}}
{{- else }}
{{ $field }}: {{ required (printf "key %s is missing" $my_key) nil }}
{{- end }}
{{- end }}
答案 1 :(得分:0)
您可以将helm lint与-strict 标志一起使用以检查未定义的值
$ helm lint --strict .
==> Linting .
[INFO] Chart.yaml: icon is recommended
[ERROR] templates/: render error in "mychart/templates/service.yaml": template: mychart/templates/service.yaml:10:19: executing "mychart/templates/service.yaml" at <.Values.foo>: map has no entry for key "foo"
Error: 1 chart(s) linted, 1 chart(s) failed
答案 2 :(得分:0)
您可以利用range
和null
无法通过所需检查的事实来做一些事情。因此,在您的values.yaml中,您可以使用此部分以获取必需的环境变量:
reqEnv:
- name: "VAR1"
value: null
- name: "VAR2"
value: null
然后在“部署”的env部分中,您将:
{{- range .Values.reqEnv }}
{{ .name }}: {{ required "A value must be entered for all reqEnv entries" .value }}
{{- end }}
然后,除非用户在其值文件中将reqEnv
部分的所有必需值设置为参数,否则将收到错误消息。不幸的是,这样做会使您失去的是缺少var的细节。这可能就是为什么the official helm charts seem to prefer using required
像以前那样的原因。
答案 3 :(得分:0)
我想出了一个替代黑客来解决这个问题。这是否真的比内置解决方案更好是值得怀疑的,但我认为这里作为一个选项可能值得一提。
向您的 _helpers.tpl(或任何地方)添加一个函数:
{{/*
Require and include a value
*/}}
{{- define "require" -}}
{{- $scope := index . 0 -}}
{{- $name := index . 1 -}}
{{required (print "Missing required value: " $name) (index $scope "Values" $name)}}
{{- end}}
然后在您的模板中调用它:
value: {{ include "require" (list . "foo") }}
如果缺少某个值,则会出现错误消息:
<块引用>缺少必需的值:foo
否则,它会插入值。
编辑:要使其适用于嵌套值,您需要一个稍微复杂的帮助器:
{{/*
Index a nested component
*/}}
{{- define "indexNested" -}}
{{- $message := index . 0 -}}
{{- $object := index . 1 -}}
{{- $path := (mustRegexSplit "\\." (index . 2) -1) -}}
{{- range $path -}}
{{- if not $object -}}
{{ fail $message }}
{{- end -}}
{{- $object = index $object . -}}
{{- end -}}
{{ required $message $object }}
{{- end}}
{{/*
Require and include a value
*/}}
{{- define "require" -}}
{{- $scope := index . 0 -}}
{{- $name := index . 1 -}}
{{ include "indexNested" (list (print "Missing required value: " $name) $scope.Values $name) }}
{{- end}}
现在您可以通过以下方式访问 foo.bar
值:
{{ include "require" (list . "foo.bar") }}