簡體   English   中英

helm 使用模板中的參數檢查 Values.yaml 中是否存在值

[英]helm using argument in template to check if value exists in Values.yaml

問題如下:我想根據 _helpers.tpl 中提供給模板的參數檢查 Values.yaml 中的字段是否存在:

{{- define "example-name" -}}
{{- $objectRef := index . 0 -}}
{{- if .Values.custom -}}
{{- if .Values.custom.$objectRef -}}
{{- if .Values.custom.$objectRef.annotations -}}
{{- include "some-library" (tuple .Values.custom.$objectRef.annotations) | indent 4 }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}

然后在我的部署中,例如:

{{- template "example-name" "someField" }}

我希望結果如下:

{{- define "example-name" -}}
{{- $objectRef := index . 0 -}}
{{- if .Values.custom -}}
{{- if .Values.custom.someField-}}
{{- if .Values.custom.someField.annotations -}}
{{- include "some-library" (tuple .Values.custom.someField.annotations) | indent 4 }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}

但我唯一得到的是以下錯誤:壞字符 U+0024 '$' 我想多次使用模板和各種 arguments。我之前沒有看到有人處理過同樣的問題。

有任何想法嗎?

您要查找的標准模板 functionindex 在其最簡單的形式中, index $map $key在提供的$map (可以是任何表達式)中動態查找$key (可以是任何表達式)。 如果需要,它還可以在 arrays(Go 切片)和嵌套查找中執行整數索引查找。

您將遇到的另一個問題是$map.undefinedKey (或index $map "undefinedKey" ),假設undefinedKey不存在於$map中,它是有效的但計算結果為 Go nil 所以你不能在那里做進一步的查找。 我通常使用的解決方法是使用 Helm (Sprig) default function 在值不存在時使用空dict

那會給你一個像這樣的模板:

{{- define "example-name" -}}
{{- $top := index . 0 -}}
{{- $objectRef := index . 1 -}}
{{- $custom := $top.Values.custom | default dict -}}
{{- $object := index $custom $objectRef | default dict -}}
{{- with $object.annotations -}}
{{- include "some-library" (list $top .) | indent 4 }}
{{- end }}
{{- end }}

這是用兩個值的列表調用的,頂級 Helm object 和對.Values.custom中的鍵的引用

{{- include "example-name" (list . "someField") -}}

該模板從列表參數中提取這兩個值。 然后它一次遍歷值結構的一個級別,在每個級別默認為一個空字典。 因此,例如,如果沒有.Values.custom$custom被設置為一個空字典,這允許index $custom $objectRef成功執行(並返回nil ,但不會中止)。 在底層,我們使用with模板 function 檢查 come 值是否為真,如果是,則暫時綁定. 到它的價值。 當我們進行內部調用時,我們已經在一個變量中有了頂層 Helm object,我們可以組裝一個$top列表和非空注解結構. 作為單個模板參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM