fir*_*ter 4 kubernetes-helm helm3
我希望能够从如下 Helm 模板文件中插入带有toJson helm 函数的模板,如文档中所述:
value: {{ include "mytpl" . | lower | quote }}
Run Code Online (Sandbox Code Playgroud)
https://helm.sh/docs/howto/charts_tips_and_tricks/#know-your-template-functions
我的配置: _helper.tpl
{{- define "my_tpl" -}}
key1: value1
key2: value2
{{- end -}}
Run Code Online (Sandbox Code Playgroud)
dep.yaml
template:
metadata:
annotations:
test: >-
{{ include "my_tpl" . | toJson }}
Run Code Online (Sandbox Code Playgroud)
这应该返回
template:
metadata:
annotations:
test: >-
{"key1":"value1","key2":"value2"}
Run Code Online (Sandbox Code Playgroud)
但它返回
template:
metadata:
annotations:
test: >-
"key1:value1\nkey2:value2"
Run Code Online (Sandbox Code Playgroud)
我正在使用 Helm v3。有人有什么想法吗?
Dav*_*aze 11
ddefine模板总是生成一个字符串;Helm 特定的include函数始终返回一个字符串。
在您的示例中,您有一个恰好是有效 YAML 的字符串。Helm 有一个未记录的fromYaml函数,可以将字符串转换为对象形式,然后您可以使用 再次序列化它toJson。
{{ include "my_tpl" . | fromYaml | toJson }}
Run Code Online (Sandbox Code Playgroud)
您可能会发现让模板本身生成正确的 JSON 序列化更容易。那可能看起来像
{{- define "my_tpl" -}}
{{- $dict := dict "key1" "value1" "key2" "value2" -}}
{{- toJson $dict -}}
{{- end -}}
{{ include "my_tpl" . }}
Run Code Online (Sandbox Code Playgroud)
其中"key1"、"value1"等可以是任何有效的模板表达式(不需要嵌套{{ ... }})。