【问题标题】:helm templating with toYaml使用 toYaml 进行 helm 模板化
【发布时间】:2020-09-30 01:57:21
【问题描述】:

我有 values.yml 文件,其中包含具有这种格式和默认值的端口列表:

Ports:
  - number: 443
    protocol: http

输出端口列表用作我的输入的脚本给了我这种格式:

port_list=$(./get_ports.sh)

输出:

- 80
- 8080

我希望生成的渲染模板是

Ports:
  - number: 80
  - number: 8080

我将如何做到这一点?我在我的模板文件中尝试了以下内容:

{{- with .Values.Ports }}
Ports:
  {{- toYaml . | nindent 8 }}
{{- end }}

使用 helm 模板并设置 values.Ports=$port_list,它最终给了我一个管道和一个额外的破折号,如下所示,我不知道它们来自哪里,我如何根据输入?

Ports:
|-
  - number: 80
  - number: 8080

作为奖励,如果未指定协议,我还希望在我的端口列表中有一个默认协议。

Ports:
  - number: 80
    protocol: http
  - number: 8080
    protocol: http

有没有一种只用模板来做到这一点的干净方法?

【问题讨论】:

  • 你的get_ports.sh可以输出其他格式吗?例如a, b, c
  • 尝试从{{- toYaml . [...]中删除-,并尝试使用indent而不是nindent
  • 我知道我来晚了,但我强烈建议反对使用toYaml,因为这意味着你突然不得不关心缩进。鉴于 YAML 是 JSON 的超集,最好只使用 Ports: {{ toJson . }} 代替。您将获得所需的结果,而不必担心空格或格式问题。
  • 非常感谢@Mr.Llama,它现在可以与 {{ toJson .}} 一起使用,正如您所说,我将获得所需的结果,而不必担心空格或格式问题。

标签: kubernetes yaml kubernetes-helm


【解决方案1】:

首先,您必须了解有关字符串的 YAML 语法。你可以通过在互联网上搜索找到它。例如:见YAML Multiline

| 启用多行字符串,- 从字符串末尾截断尾随 \n

出现|- 的原因是脚本get_ports.sh 的输出(被视为单个字符串)。你可以测试一下,

port_list=$(get_ports.sh)
# pass this to the `--set` flag in both of the following ways
# 01: pass the var $port_list
--set ports=$port_list
# 02: directly pass the value of the var $port_list
--set ports="- 80
- 8080"

对于这两个测试,您的输出相同,如下所示:

ports:
|-
  - 80
  - 8080

如果您在脚本输出的末尾添加一个换行符,那么您将看到 - 消失了。

--set ports="- 80
- 8080
"

输出如下:

ports:
|
  - 80
  - 8080

现在尝试不同的方式。将您的模板更改为这样的:

{{- if .Values.ports }}
  {{- print "ports:" | nindent 2 }}
  {{- range $_, $p := .Values.ports }}
    - number: {{ $p }}
      protocol: http
  {{- end }}
{{- end }}

此模板需要--set 标志中的端口值作为列表(而不是字符串)。根据我在撰写此答案时的知识,要在 --set 标志中提供列表值,可以使用以下任一选项:

  • --set ports={80\,8080}
  • --set ports[0]=80,ports[1]=8080

现在输出和你想要的一样。

$ helm template test . --set ports={80\,8080}
ports:
  - number: 80
    protocol: http
  - number: 8080
    protocol: http

所以你只需要处理get_ports.sh 的输出。就是这样。

您可能需要调整模板中的缩进

【讨论】:

  • 很好的答案,谢谢。这正是我所需要的。
猜你喜欢
  • 2018-05-18
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2019-12-31
  • 2019-09-21
相关资源
最近更新 更多