我正在阅读有关如何为 Kubernetes 执行一些循环的 helm 文档,基本上我想做的是类似于 this 的事情。
我有什么...
values.yaml
dnsAliases:
- test1
- test2
- test3
在services-external.yaml
{{- if and .Values.var1.var1parent (eq .Values.var2.var2parent "value") }}
{{- range .Values.dnsAliases }}
apiVersion: v1
kind: Service
metadata:
name: name-{{ . }} ( for creating the name "name-test1/test2 and so on"
spec:
type: ExternalName
externalName: {{ .Values.var3.var3parent }}-{{ .Values.var4.var4parent }}-{{ .}}.svc.cluster.local
ports:
- port: 80
protocol: TCP
targetPort: 80
{{ end }}
{{ end }}
但我有错误
Error: UPGRADE FAILED: render error in "services-external.yaml": template: templates/services-external.yaml:312:32: executing "services-external.yaml" at <.Values.var3.var3parent>: can't evaluate field Values in type interface {}
我也尝试过使用“with”但同样的错误。有没有办法通过在 helm 上使用带有循环的“if”来实现它?
答案 0 :(得分:0)
您遇到的错误表明模板无法找到 <.Values.var3.var3parent>
的值。由于您使用的是 range
块,因此 .
指的是循环内的局部变量。您需要引用全局变量。这可以通过两种方法实现:
$
(使用 var3
查看)var4
查看)这是一个经过测试的模板,其中包含上述两种方法:
{{- if and .Values.var1.var1parent (eq .Values.var2.var2parent "value") }}
{{- $var4 := .Values.var4 -}}
{{- range .Values.dnsAliases }}
apiVersion: v1
kind: Service
metadata:
name: name-{{ . }} ( for creating the name "name-test1/test2 and so on"
spec:
type: ExternalName
externalName: {{ $.Values.var3.var3parent }}-{{ $var4.var4parent }}-{{ .}}.svc.cluster.local
ports:
- port: 80
protocol: TCP
targetPort: 80
{{ end }}
{{ end }}
你可以阅读更多here
另外还有一种可能的解决方案可以将范围重置为 root 并像往常一样使用循环(但它的方法更粗略)(here's a link)
答案 1 :(得分:0)
感谢@moonkotte,我设法使用定义新变量来保存范围的方法使其工作,这里是示例。
在values.yaml
dnsShortNames:
short1: "short1"
short2: "short2"
short3: "short3"
dnsAliases:
- test1
- test2
- test3
在services-external.yaml
{{- $dns_short_names := .Values.dnsShortNames }}
{{- range .Values.dnsAliases }}
---
apiVersion: v1
kind: Service
metadata:
name: name-{{ . }}
spec:
type: ExternalName
externalName: {{ $dns_short_names.short1 }}-{{ $dns_short_names.short2 }}-{{ $dns_short_names.short3 }}{{.}}.svc.cluster.local
ports:
- port: 80
protocol: TCP
targetPort: 80
{{- end }}
应用此 Kubernetes 将创建 3 种不同的外部服务。
short1-short2-short3.test1.svc.cluster.local
short1-short2-short3.test2.svc.cluster.local
short1-short2-short3.test3.svc.cluster.local
公开感谢我的朋友哈维 <3.