Helm模板中如何实现同名配置属性的覆盖而非追加?
解决方案
要实现同名配置属性覆盖而非追加,需要先将两个配置块的内容解析为键值对字典,合并时让runtimePropertiesExtra的配置覆盖runtimeProperties的同名项,最后再转换回多行字符串格式。修改后的模板代码如下:
runtime.properties: | {{- /* 解析runtimeProperties为键值对字典 */ -}} {{- $baseProps := dict -}} {{- with .Values.broker.runtimeProperties -}} {{- range splitList "\n" . -}} {{- $line := trim . -}} {{- if and $line (not (hasPrefix "#" $line)) -}} {{- $parts := split "=" $line -}} {{- if eq (len $parts) 2 -}} {{- $key := trim (index $parts 0) -}} {{- $value := trim (index $parts 1) -}} {{- $baseProps = merge $baseProps (dict $key $value) -}} {{- end -}} {{- end -}} {{- end -}} {{- end -}} {{- /* 解析runtimePropertiesExtra为键值对字典 */ -}} {{- $extraProps := dict -}} {{- with .Values.broker.runtimePropertiesExtra -}} {{- range splitList "\n" . -}} {{- $line := trim . -}} {{- if and $line (not (hasPrefix "#" $line)) -}} {{- $parts := split "=" $line -}} {{- if eq (len $parts) 2 -}} {{- $key := trim (index $parts 0) -}} {{- $value := trim (index $parts 1) -}} {{- $extraProps = merge $extraProps (dict $key $value) -}} {{- end -}} {{- end -}} {{- end -}} {{- end -}} {{- /* 合并字典,extraProps覆盖baseProps的同名键 */ -}} {{- $mergedProps := mergeOverwrite $baseProps $extraProps -}} {{- /* 将合并后的字典转换为多行配置 */ -}} {{- range $k, $v := $mergedProps -}} {{ $k }}={{ $v }} {{- end -}}
代码说明:
- 解析配置为字典:分别将
runtimeProperties和runtimePropertiesExtra的多行字符串按行分割,过滤空行和注释行后,拆分为键值对存入字典。 - 合并字典:使用
mergeOverwrite函数,让runtimePropertiesExtra的键值对覆盖runtimeProperties中的同名项。 - 生成最终配置:遍历合并后的字典,输出为
key=value格式的多行字符串,保持正确缩进。
执行helm template -f 1st_values.yaml -f 2nd_values.yaml .后,即可得到期望的输出:
druid.server.http.numThreads=180 druid.broker.http.numConnections=500 druid.sql.enable=true
内容的提问来源于stack exchange,提问作者Alexy Pulivelil
相关产品推荐
相关产品推荐

