我似乎無法找到一個簡單有效的解決方案來解決我想象的 Go 模板/Helm 中經常出現的問題。基本上,給定一個像這樣的values.yaml:ingress: hosts: - host: busy-a.local paths: - backend: serviceName:busy-a servicePort: 80 path: /busy/[A-Z0-9]{1}和 templates/ingress.yaml 像這樣:apiVersion: extensions/v1beta1kind: Ingressmetadata: name: {{.Values.project}}-ingress annotations: nginx.ingress.kubernetes.io/use-regex: "true"spec: rules: {{- range .Values.ingress.hosts }} - host: {{ .host | quote }} http: paths: {{- range .paths }} - path: {{ .path }} backend: serviceName: {{ .backend.serviceName }} # this works servicePort: {{ .backend.servicePort }} # but can we shorthand backend? {{- end }} {{- end }}backend但是,在 中“解壓”地圖不是更容易.paths range嗎backend: {{.backend}}?然而,它似乎并不是那樣工作的。... paths: - path: /busy/[A-Z0-9]{3} backend: map[serviceName:busy-a servicePort:80]在 Go 模板或 Sprig 擴展中解壓或分配整個對象的首選方法是什么?
1 回答

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
Helm 有幾個幾乎沒有記錄的功能,其中之一是toYaml
.?它接受任意對象并以 YAML 格式寫出,不縮進。
toYaml
在您的情況下,您可以通過組合和來實現您想要的目標indent
:
spec:
? ...
? ? ? ? ? ? backend:
{{ .backend | trim | indent 14 }}
{{/* above line intentionally at left margin */}}
由于toYaml可以很好地處理嵌套對象,因此考慮到您的輸入和輸出,我可能會將其應用到更高的位置:
spec:
? rules:
? {{- range .Values.ingress.hosts }}
? ? - host: {{ .host | quote }}
? ? ? http:
? ? ? ? paths: {{- .paths | toYaml | trim | nindent 10 }}
? {{- end }}
toYaml總是會發出一個尾隨的換行符,所以我傾向于將trim其關閉,這樣我就可以更好地控制它。在最后一個示例中,我使用nindent插入前導換行符來使模板更加緊湊。
- 1 回答
- 0 關注
- 151 瀏覽
添加回答
舉報
0/150
提交
取消