在Go模板中使用包含内部范围(头盔)

时间:2020-04-18 22:31:27

标签: kubernetes-helm go-templates

我有一个模板,可以通过range迭代多次渲染,并且可以毫无问题地访问变量$.Release.Name等外部变量。但是,当我包含模板时,无法使其正常工作:

{{ range $key, $val := $.Values.resources }}
      ...
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/secrets.yaml") . | sha256sum }}
{{ end }}

secrets.yaml中:

apiVersion: "v1"
kind: "Secret"
metadata:
  name: {{ $.Release.Name }}-secrets

我收到此错误:

Error: render error in "botfront-project/templates/deployment.yaml": template: [filename] :19:28: executing [filename] at <include (print $.Template.BasePath "/secrets.yaml") .>: error calling include: template: .../secrets.yaml:4:19: executing ".../secrets.yaml" at <$.Release.Name>: nil pointer evaluating interface {}.Name

如何访问包含的模板中的变量?

1 个答案:

答案 0 :(得分:7)

TL; DR;

只需将.替换为$,以使用全局范围而不是您创建的本地范围。

示例:

{{- include "my-chart.labels" $ | nindent 4 }}

说明

根据文档https://helm.sh/docs/chart_template_guide/control_structures/#modifying-scope-using-with

我们可以使用$从父级访问对象Release.Name 范围。 开始执行模板时,$映射到根作用域 并且它在模板执行期间不会改变

使用range,我们可以在循环内更改范围。实际上,{{- include "my-chart.labels" . | nindent 4 }}会调用当前范围.

因此,如果您在掌舵文档中深入研究“范围”一词,最终您会找到以下部分:https://helm.sh/docs/chart_template_guide/variables/

在此示例中:

{{- range .Values.tlsSecrets }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ .name }}
  labels:
    # Many helm templates would use `.` below, but that will not work,
    # however `$` will work here
    app.kubernetes.io/name: {{ template "fullname" $ }}
    # I cannot reference .Chart.Name, but I can do $.Chart.Name
    helm.sh/chart: "{{ $.Chart.Name }}-{{ $.Chart.Version }}"
    app.kubernetes.io/instance: "{{ $.Release.Name }}"
    # Value from appVersion in Chart.yaml
    app.kubernetes.io/version: "{{ $.Chart.AppVersion }}"
    app.kubernetes.io/managed-by: "{{ $.Release.Service }}"
type: kubernetes.io/tls
data:
  tls.crt: {{ .certificate }}
  tls.key: {{ .key }}
---
{{- end }}