我正在寻找在 helm 中合并两个值文件。
secrets.yaml:
oracle_db:
serviceMonitor:
endpoints:
- module: oracledb
port: http
scheme: http
url: "http://user:password@ip:port/xxx"
我有另一个 value.yaml 文件,它有多个端点。我想合并两个值文件。我尝试使用附加函数来执行此操作:
{{$endpoints := (append .Values.serviceMonitor.endpoints .Values.oracle_db.serviceMonitor.endpoints) }}
当我进行空运行时,我看到它获取了两个值,但不会合并。有人遇到过这个吗?
在当前的 Helm 版本 (3) 中不支持合并值。
此功能在 Github 问题中进行了讨论:Helm 应对多个值文件执行深度合并。
其中的一句重要引言
如果实现了这一点,它应该是可选的,即。 e.合并模式应指定为命令行标志。其他任何事情都将是一个破坏性的改变,而且我认为在大多数情况下是不可取的。问题是您无法覆盖列表的默认值。
参见:https://github.com/helm/helm/issues/3486#issuecomment-364534501
您可以使用 python 脚本在传递值文件之前合并它们。下面是我正在使用的代码片段。
import yaml
from deepmerge import always_merger
fileA = “tmp.yaml"
fileB = “feature.yaml"
with open(fileA,'r+') as f:
fileAdictionary= yaml.load(f)
with open(fileB,'r+') as f:
fileBdictionary = yaml.load(f)
result = always_merger.merge(fileAdictionary, fileBdictionary)
with open(‘newFile.yaml’,'w+') as f:
yaml.dump(result,f)
另一种选择:
{{- define "template.valueOrDefault" -}}
{{- $value := dict -}}
{{- range (rest .) -}}
{{- $value = merge $value . -}}
{{- end -}}
{{- if $value -}}
{{- printf "%s:" (first .) }}
{{- toYaml $value | nindent 2 }}
{{- end }}
{{- end -}}
用途:
containers:
- name: db-migrations-job
{{- include "template.valueOrDefault" (list "resources" .Values.migrationJob.resources .Values.resources) | nindent 8 }}
这是一个简单的 python 脚本,用于合并 value.yaml 文件,并尽最大努力保留注释、格式和项目顺序。
https://github.com/Aref-Riant/yaml-merger-py
用途:
python yaml-merger.py file1.yaml file2.yaml > mergedfile.yaml
另一种方法是使用
yq
:
cat base.yaml
foo: bar
foo2:
key1: baz
key2: rar
cat extend.yaml
foo: none
foo2:
key1: yes
key3: no
像这样合并它们:
yq -n 'load("base.yaml") * load("extend.yaml")'
结果将是:
foo: none
foo2:
key1: yes
key2: rar
key3: no
请注意,文件的顺序很重要,因为第二个参数将扩展第一个参数。 yq 也很方便,因为它已经包含在
alpine/helm
图像中。