使用动态值列表进行 Helm dig

问题描述 投票:0回答:1

我正在尝试使用 helm 中的 dig 函数来检查字典中是否存在某个值,我有一个以空格分隔的字符串,我想将其用作要在字典中检查的每个键。

例如,如果不添加值文件,它应该像这样:

{{- $mydict := (dict "A" (dict "B" ( dict "C" "Present"))) -}}
{{- $string := "\"A\" \"B\" \"C\"" -}}
{{- $vals := dig $string "not present" $mydict -}}
{{- if eq $vals "not present" }}
{{- fail (printf "Failed to find value") }}
{{- end }}

有没有办法扩展dig读取的字符串?我尝试将字符串更改为列表,但这似乎也没有帮助。

kubernetes-helm go-templates sprig-template-functions
1个回答
0
投票

我不认为有什么好的方法可以做到这一点。

这里的核心问题是

dig
将其路径视为一系列位置参数,但没有“apply”函数可以注入可变数量的参数。

{{- $s1 := "A" -}}
{{- $l1 := splitList " " $s1 -}}
{{- dig (index $l1 0) "not present" $mydict }}

{{ $s2 := "A B" -}}
{{- $l2 := splitList " " $s2 -}}
{{- dig (index $l2 0) (index $l2 1) "not present" $mydict }}

请注意,两个

dig
调用具有不同数量的参数,我们需要手动扩展列表。这在其他语言中是可能的(例如,Python 有一种方法来构造参数列表,然后用它调用函数),但在 Go 模板语言中则不行。

我通常使用递归模板函数来解决这个问题。让模板参数为一个列表,其中第一个值是您正在遍历的数据结构,其余值是路径。然后你就可以走下去了。

{{- define "find" -}}
  {{- if eq (len .) 1 -}}
    {{- if (index . 0) -}}
      present
    {{- else -}}
      not present
    {{- end -}}
  {{- else -}}
    {{- $d := index (index . 0) (index . 1) | default dict -}}
    {{- $l := slice . 2 -}}
    {{- include "find" (prepend $l $d) -}}
  {{- end -}}
{{- end -}}

这仍然有问题;例如,模板函数只能返回一个字符串,因此如果您想选取嵌套映射的一部分,则无法返回它。

© www.soinside.com 2019 - 2024. All rights reserved.