kubernetes-helm - 在 Helm 模板中定义一个变量

标签 kubernetes-helm go-templates

我需要根据 if 语句定义一个变量并多次使用该变量。
为了不重复 if 我尝试了这样的事情:

{{ if condition}}
    {{ $my_val = "http" }}
{{ else }}
    {{ $my_val = "https" }}
{{ end }}
{{ $my_val }}://google.com

但是这会返回一个错误:
Error: render error in "templates/deployment.yaml":
template: templates/deployment.yaml:30:28:
executing "templates/deployment.yaml" at
<include (print $.Template.BasePath "/config.yaml") .>: error calling
include: template: templates/config.yaml:175:59:
executing "templates/config.yaml" at <"https">: undefined variable: $my_val

想法?

最佳答案

最直接的方法是使用 ternary 函数 provided by the Sprig library 。那会让你写一些类似的东西

{{ $myVal := ternary "http" "https" condition -}}
{{ $myVal }}://google.com

一个更简单但更间接的路径是编写一个模板来生成值,并调用它
{{- define "scheme" -}}
{{- if condition }}http{{ else }}https{{ end }}
{{- end -}}

{{ template "scheme" . }}://google.com

如果您需要将其包含在另一个变量中,Helm 提供了一个 include 函数,它的作用与 template 类似,只是它是一个“表达式”而不是直接输出的东西。
{{- $url := printf "%s://google.com" (include "scheme" .) -}}

关于kubernetes-helm - 在 Helm 模板中定义一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56324405/

相关文章:

kubernetes - 在 Kubernetes 上安装 nginx-ingress 以在 localhost MacOs 上运行 - Docker for Mac(Edge)

kubernetes - 如何在伞形图的一部分中安装linkerd?

docker - 如何从Kubernetes Pod访问HDP集群

resources - 如何通过一个命令从Helm列表中删除所有资源?

kubernetes - 版本 “v1”中的部署不能作为部署处理:

go - 如何比较go模板中的字符串?

go - 将数据和变量传递到模板

html - Go - 不呈现 HTML 注释

templates - 如何从已解析的模板中获取模板 'actions' 的 map 或列表?

go - 如何将当前年份添加到 Go 模板中?