How do I pass a map as a Helm tpl string?

Viewed 34

I'm trying to populate the annotations on a service which is templated like this:

apiVersion: v1
kind: Service
metadata:
  name: example
  namespace: {{ .Release.Namespace }}
  annotations:
    {{- if .Values.service.annotations }}
    {{ tpl .Values.service.annotations . | nindent 4 | trim }}
    {{- end }}

(rest omitted for brevity.)

I tried to populate the service.annotations like this in my values.yaml:

service:
  annotations:
    foo: my-foo
    bar: 6
    baz: false

... but Helm errored out with [ERROR] templates/: template: my-chart/templates/service.yaml:20:18: executing "my-chart/templates/service.yaml" at <.Values.service.annotations>: wrong type for value; expected string; got map[string]interface {}

I tried reading the docs for the tpl function but they just showed examples for how to interpolate a string from a different variable, or how to pass values from an external file.

How do I set the annotations on this service? I don't have any control over the template.

1 Answers

update

You need to understand the essence of the problem, my previous answer is the style required for the final rendering, based on this, you just need to understand the usage of tpl and try to render the template as written before.

helm tpl

values.yaml

service:
  annotations: "{{ toYaml .Values.service.fields | trim }}"
  fields:
    foo: my-foo
    bar: 6
    baz: false

template

apiVersion: v1
kind: Service
metadata:
  name: example
  namespace: {{ .Release.Namespace }}
  annotations:
    {{- if .Values.service.annotations }}
    {{ tpl .Values.service.annotations . | nindent 4 | trim }}
    {{- end }}
...

cmd

helm template --debug test .

output

apiVersion: v1
kind: Service
metadata:
  name: test
  namespace: default
  annotations:
    bar: 6
    baz: false
    foo: my-foo
...

As David Maze said.
In service.yaml, annotations must be a YAML string.

You may try
tempaltes/service.yaml

apiVersion: v1
kind: Service
metadata:
  name: example
  namespace: {{ .Release.Namespace }}
  {{- if .Values.service.annotations }}
  annotations:  
    {{ toYaml .Values.service.annotations | nindent 4 | trim }}
  {{- end }}
Related