使用带有 helm 模板的 yaml 数组

Using a yaml array with helm template

我有一个代表 Helm 图表的目录结构如下:

Chart.yaml
values.yaml
templates/
  template.tpl

values.yaml:

foo: ["bar", "baz"]

FOO:
 - BAR
 - BAZ

templates/template.tpl:

thing1: {{ .Values.foo }}
thing2: {{ .Values.FOO }}

运行 helm template . 的输出在此目录中。 (Helm 版本 v3.6.3)

---
# Source: test/templates/template.tpl
thing1: [bar baz]
thing2: [BAR BAZ]

你可以在这里看到 thing1 和 thing2 都映射到 YAML 数组,每个数组包含一个字符串,即字符串 "bar baz""BAR BAZ".

我希望数组中的项目在模板化后仍然是单独的字符串。但是我在 helm 模板语言文档中找到的内置函数(如 {{ list .Values.foo }})没有做任何有成效的事情。

有人可以告诉我如何正确地模板化 YAML 字符串数组吗?

Helm 使用 Go 模板,而 Go 模板不知道 YAML。因此它只会以 Go 的默认格式发出 sequence(YAML 没有数组),恰好是 [<item> ...].

您需要告诉 Helm 将值转换为 YAML 格式:

thing1: {{ .Values.foo | toYaml | nindent 2 }}
thing2: {{ .Values.FOO | toYaml | nindent 2 }}

toYaml 进行实际转换(它是 kind-a undocumented),nindent 2 添加一个换行符,然后每行缩进 2 个空格。当 toYaml 选择将您的输入呈现为多行时,这一点很重要,您无法控制。