使用 helm 模板助手创建过滤列表

Yar*_*dan 3 go-templates kubernetes kubernetes-helm sprig-template-functions

我正在尝试使用 helm 模板助手values.yaml根据每个列表成员中的一个键的值从我的文件中的列表中过滤掉值。

我的图表目前由这些文件组成 -
values.yaml -

namespaces:
- name: filter
  profiles:
  - nonProduction
- name: dont-filter
  profiles:
  - production  
clusterProfile: production
Run Code Online (Sandbox Code Playgroud)

模板/命名空间.yaml

apiVersion: v1
kind: List
items:
{{ $filteredList := include "filteredNamespaces" . }}
{{ range $filteredList }}
  {{ .name }}
{{- end -}}
Run Code Online (Sandbox Code Playgroud)

模板/_profile-match.tpl

{{/* vim: set filetype=mustache: */}}
{{- define "filteredNamespaces" -}}
  {{ $newList := list }}
  {{- range .Values.namespaces }}
    {{- if has $.Values.clusterProfile .profiles -}}
      {{ $newList := append $newList . }}
    {{- end -}}
  {{ end -}}
  {{ $newList }}
{{- end -}}
Run Code Online (Sandbox Code Playgroud)

问题是在我的帮助文件中,$newList变量只填充在range循环范围内,我最终得到一个返回namespaces.yaml模板的空列表。
有没有办法解决这个问题?我是否采取了错误的方法来解决这个问题?

Dav*_*aze 8

尽管 Go 模板几乎都是通用函数,但它们有一些限制。这些限制之一是它们只返回一个字符串;你不能像mapfilter因为你不能返回结果列表一样编写基本的功能助手。

正如您所展示的,进行过滤的更直接的方法是将其移动到调用者的位置(如果在多个地方需要,可能会重复该条件):

items:
{{- range .Values.namespaces }}
{{- if has $.Values.clusterProfile .profiles }}
  - {{ .name }}
{{- end }}
{{- end }}
Run Code Online (Sandbox Code Playgroud)

使这项工作如您所愿的一种hacky 方法是将列表编组为其他一些基于字符串的格式,例如 JSON:

{{- define "filteredNamespaces" -}}
...
{{ toJson $newList }}
{{- end -}}

{{- range include "filteredNamespaces" . | fromJson -}}...{{- end -}}
Run Code Online (Sandbox Code Playgroud)

还请记住,您可以使用该helm install -f选项注入 Helm 值文件。因此,与其列出选项的每个排列,然后过滤掉您不想要的排列,您还可以对其进行重组,使其namespaces:仅包含您实际想要使用的命名空间列表,然后您为每个配置文件使用不同的值文件。


rin*_*ahn 6

我不得不处理一个非常相似的问题。我给出了一个如何过滤生成的模板并将其用作列表的最小示例(Helm 3)。

_helpers.tpl

{{- define "FilteredList" -}}

  {{ $newList := list }}
  {{- range .Values.my_list }}
    {{ $newList = append $newList .pvc }}
  {{- end }}

  {{ toJson $newList }}
{{- end }}
Run Code Online (Sandbox Code Playgroud)

pvc.yaml

{{- range include "FilteredList" . | fromJsonArray }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: {{ . }}
spec:
  resources:
    requests:
      storage: 1G
---
{{- end }}
Run Code Online (Sandbox Code Playgroud)

values.yaml

my_list:
  - name: foo
    pvc: pvc-one
  - name: foo2
    pvc: pvc-two
  - name: foo3
    pvc: pvc-three
Run Code Online (Sandbox Code Playgroud)

如您所料,生成 3 个 PVC 资源。
请注意这里的两件事,它们与问题和接受的答案不同: