kuberneteskubernetes-helmgo-templates

toYaml in helm template inside range causes error converting YAML to JSON


I am tryint to populate my deployment from values and getting error:

YAML parse error on helm-general/templates/deployment.yaml: error converting YAML to JSON: yaml: line 46: mapping values are not allowed in this context

My values.yaml

env:
  LIMESURVEY_DB_HOST: 
    value: "host.com"
  LIMESURVEY_DB_PASSWORD: 
    valueFrom:
      secretKeyRef:
        name: limesurvey-pass
        key: pass

deployment.yaml

        env:
          {{- range $k, $v := .Values.env }}
          - name: {{ $k }}
            {{- $v | toYaml | indent 7 }}
          {{- end }}

Solution

  • There's a missing newline in the output. There's two ways around this. One is to use the nindent function instead of indent, which also inserts a leading newline

          - name: {{ $k }}
            {{- $v | toYaml | nindent 7 }}
    

    The other takes a little more careful consideration of whitespace. indent will insert spaces at the start of every line, including the first one, so a line that includes indent shouldn't itself be indented. You do need the newline before it, so you do not want the Go template - whitespace control marker. This leads you to

          - name: {{ $k }}
    {{ $v | toYaml | indent 7 }}
    

    (The indentation matters, it is not a typo that the second line is not indented.)

    Since you're just trying to reproduce an entire block from the values as-is, you also don't need the range loop, which could avoid a little bit of complexity here.

    spec:
      template:
        spec:
          containers:
            - env:
    {{ .Values.env | toYaml | indent 12 }}