kubernetes-helm - 在 Helm 模板中定义一个变量
问题描述
我需要根据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
想法?
解决方案
最直接的方法是使用Sprig 库提供的ternary
函数。那会让你写类似的东西
{{ $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" .) -}}
推荐阅读
- java - 如何更正创建 JPQL 请求?
- android - 共享内容:使用 Intent.createChooser 时的 Permission Denial
- php - PHP - 浮点数 - 逗号和点问题
- datatables - dataTables 日期排序和 MomentJS
- javascript - 使用 Firebase 中的对象列表更新 DOM
- python-3.x - 慢序列化过程Django rest框架
- c# - pdf提取到带有unicode字符的docx C#
- c# - VB 到 C# 的转换错误(assign 和 if 语句)
- sql - 如何根据 Oracle 中用户的输入创建动态视图?
- c++ - Sublime text 3 在编译时出错