Helm模板需要在dict中获取并设置值



我的函数$newdict 中有以下数据

modules:
module1: 
enabled: true
module2:
enabled: false
module3:
enabled: true, etc

需要做的是:检查模块1是否已启用,然后为模块2设置已启用。我在_helpers.tpl文件中尝试的内容:

{{- range $key, $value := $newdict -}}
{{ if and (eq $key "module1") (eq "enabled" "true") }}
{{ $_ := set $newdict $key "module2" (eq "enabled" "true") }} 
{{ end }}  
{{ end }}
{{ toYaml $newdict }}

helm-lint没有显示任何错误,但这些变化没有反映在$newdict 中

deployment.yaml需要这个东西来部署init容器:

initContainers:
{{- $mycustom := (include "myfunction" . ) | fromYaml}}
{{- range $key, $value := $mycustom }}
{{- if $value.enabled }}
- name: init-{{ $key }}-myinit

所以,最后,我需要部署init container"模块2";仅当";模块1";还部署了

Helm的一般风格是值是不可变的。在这里我会避免使用set函数,而使用更实用的样式。

可以直接在dict(map(结构中对事物进行索引,或者使用标准的Go模板index函数,这可能有助于您的设置。您不需要遍历整个dict来查找密钥。因此,如果您确定变量具有关键字module1module2,则可以将最终逻辑简化为:

initContainers:
{{- if or .Values.module1.enabled .Values.module2.enabled }}
- name: init-module2-myinit
...
{{- end }}

您的设置提示您要有更多的init容器;module1module2module3都有自己的init容器,但无论module2设置如何,只要module1处于打开状态,您也希望发出module2的。解决这一问题的一种方法可能是编写一个辅助函数,决定是否启用给定的模块:

{{/* Decide whether some module is enabled.  Call with a list of
two items, the values structure to examine and the specific
module key.  Returns either the string "true" or an empty
string. */}}
{{- define "is-module-enabled" -}}
{{- $modules := index . 0 -}}
{{- $key := index . 1 -}}
{{- if index $modules $key "enabled" -}}
true
{{- else if and (eq $key "module2") $modules.module1.enabled -}}
true
{{- end -}}
{{- end -}}
initContainers:
{{- range $key := .Values.modules -}}
{{- if include "is-module-enabled" (list .Values.modules $key) }}
- name: init-{{ $key }}-myinit
...
{{- end }}
{{- end }}

最新更新