Golang template (helm) iterating over a list of maps
Solution 1
Inside the loop the value of the .
is set to the current element and you have to use $.Chart.Name
to access your data.
I asked a similar question and I think the answer https://stackoverflow.com/a/44734585/8131948 will answer your question too.
Solution 2
I ended up saving the global context and then updating all of my references like this:
{{ $global := . }}
{{ range $i, $job := .Values.jobs -}}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ template "name" $global }}-{{ $job.name }}
labels:
chart: "{{ $global.Chart.Name }}-{{ $global.Chart.Version | replace "+" "_" }}"
spec:
activeDeadlineSeconds: {{ $job.activeDeadlineSeconds }}
template:
metadata:
labels:
app: {{ template "name" $global }}-{{ $job.name }}
spec:
containers:
- name: {{ $global.Chart.Name }}
image: "{{ $global.Values.image.repository }}:{{ $global.Values.image.tag }}"
imagePullPolicy: {{ $global.Values.image.pullPolicy }}
command: {{ $job.command }}
env:
{{ toYaml $global.Values.service.env | indent 10 }}
ports:
- containerPort: {{ $global.Values.service.internalPort }}
{{- end }}
Victor Trac
Updated on February 20, 2021Comments
-
Victor Trac about 3 years
I'm using helm to generate kubernetes yamls.
My values.yaml looks like this:
... jobs: - nme: job1 command: [sh, -c, "/app/deployment/start.sh job1"] activeDeadlineSeconds: 600 - name: job2 command: [sh, -c, "/app/deployment/start.sh job2"] activeDeadlineSeconds: 600 ...
templates/jobs.yaml
{{ range $i, $job := .Values.jobs -}} apiVersion: batch/v1 kind: Job metadata: name: {{ template "name" . }}-{{ $job.name }} labels: chart: "{{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}" spec: activeDeadlineSeconds: {{ $job.activeDeadlineSeconds }} template: metadata: labels: app: {{ template "name" . }}-{{ $job.name }} spec: containers: - name: {{ .Chart.Name }} image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} command: {{ $job.command }} env: {{ toYaml .Values.service.env | indent 10 }} ports: - containerPort: {{ .Values.service.internalPort }} {{- end }}
Helm is failing with this error:
Error: UPGRADE FAILED: render error in "app1/templates/jobs.yaml": template: app1/templates/_helpers.tpl:6:18: executing "name" at <.Chart.Name>: can't evaluate field Name in type interface {}
When I look at _helpers.tpl:
{{- define "name" -}} {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}} {{- end -}}
If I remove the range loop and references to $job in my
jobs.yaml
, the _helpers.tplname
template works fine. When I add in the loop, it fails.It seems like within the loop, all dot
.
pipeline, which contains the scope for.Chart
and.Values
, is reassigned to something else.What am I doing wrong?