登录
首页 >  Golang >  Go问答

创建一个辅助函数以在helm Chart中使用

来源:stackoverflow

时间:2024-02-11 23:09:22 100浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《创建一个辅助函数以在helm Chart中使用》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我正在尝试创建另一个使用现有辅助函数的辅助函数,但这似乎不起作用。

我在 _helpers.tpl 文件中有以下函数:

{{- define "redis.fullname" -}}
{{- if .values.fullnameoverride -}}
{{- .values.fullnameoverride | trunc 30 | trimsuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .release.name .chart.name | trunc 30 | trimsuffix "-" -}}
{{- end -}}
{{- end -}}

现在我尝试添加另一个函数来使用上述函数为 redis 构建连接字符串:

{{ - define "redis.connection_string" -}}
{{ - printf "redis://%s:%s/" include "redis.fullname" .value.port -}} # this line is important. can we use above function like this?
{{ -end -}}

这是我的 _helpers.tpl 文件的最终内容:

{{- define "redis.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 30 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 30 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}


{{ - define "redis.connection_string" -}}
{{ - printf "redis://%s:%s/" include "redis.fullname" .Value.port -}}
{{ - end -}}

go 和 helm 对​​我来说都是新的,所以无法找出正确的 synatx,即使它可能。 (这就是我们在同一个帮助文件中编写两个函数的方式吗?)任何人都可以在这里提供帮助。


正确答案


应该可以,这是我在_helpers中定义的 (确保您使用的是 values,而不是 value)

{{- define "tpl-example.fullname" -}}
{{- if .values.fullnameoverride -}}
{{- .values.fullnameoverride | trunc 30 | trimsuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .release.name .chart.name | trunc 30 | trimsuffix "-" -}}
{{- end -}}
{{- end -}}

{{- define "tpl-example.connection_string" }}
{{- printf "redis://%s:%d/" (include "tpl-example.fullname" .) .values.port }}
{{- end }}

然后我在服务清单中使用它:

apiversion: v1
kind: service
metadata:
  name: {{ include "tpl-example.fullname" . }}
  labels:
    {{- include "tpl-example.labels" . | nindent 4 }}
    test: {{ include "tpl-example.connection_string" . }}

然后,如果我使用 helm template -s templates/service.yaml myapp ./tpl-example --set port=1111 渲染模板,它会生成以下输出:

...
    test: redis://MYAPP-tpl-example:1111/
...

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>