Home > Blockchain >  How to return complex (dict) value from Kubernetes Helm function?
How to return complex (dict) value from Kubernetes Helm function?

Time:02-21

I want to return a complex value (dict) from a Helm function, so that I can do further processing in the template or other functions.

I have defined this function:

{{- define "return-dict-function" -}}
key1: value1
key2: value2
{{- end -}}

And I can output the function value in my template:

{{ include "return-dict-function" . | nindent 2 }}

But how can I do further processing with the data?

CodePudding user response:

There are several solutions to return complex values and do further processing:

1) function returns plain yaml

Take the example function return-dict-function from the question. If you use fromYaml you'll get a dict:

{{ $dict := include "return-dict-function" . | fromYaml }}
type: {{ $dict | typeOf }}
{{- range $key, $value := $dict }}
simple-function-{{ $key }} : processed-value-{{ $value }}
{{- end -}}

Output:

type: map[string]interface {}
simple-function-key1 : processed-value-value1
simple-function-key2 : processed-value-value2

2) function needs to return dict

a) serialize to json

If you have a dict which should be returned you can serialize the dict with toJson

{{- define "return-dict-function-json" -}}
{{- $result := dict "key1" "value1" "key2" "value2" }}
{{- $result | toJson  -}}
{{- end -}}

Later you will deserialize with fromJson

{{ $dict := include "return-dict-function-json" . | fromJson }}
{{- range $key, $value := $dict }}
json-function-{{ $key }} : processed-value-{{ $value }}
{{- end -}}

b) serialize to yaml

You can also serialize the dict with toYaml

{{- define "return-dict-function-yaml" -}}
{{- $result := dict "key1" "value1" "key2" "value2" }}
{{- $result | toYaml  -}}
{{- end -}}

Then you need to deserialize with fromYaml

{{ $dict := include "return-dict-function-yaml" . | fromYaml }}
{{- range $key, $value := $dict }}
yaml-function-{{ $key }} : processed-value-{{ $value }}
{{- end -}}

Notes and further readings

  • Related