helm template: how do i assign the result of a template to a variable

9/20/2018

I'm trying to do something like:

{{- $cassandrafullname := template "cassandra.fullname" . -}}

but I'm getting this error on a dry run:

Error: UPGRADE FAILED: parse error in "cassandra/templates/service.yaml": template: cassandra/templates/service.yaml:1: unexpected <template> in command

The reason why I have this issue is because I am unable to use the template cassandra.fullname within a range, so I'm trying to put the value into a variable and use it in the range instead. So if there's a solution for that, it would also be accepted!

-- Mike
go-templates
kubernetes-helm

2 Answers

1/28/2020

Unfortunately this does not work with fromYaml, so you can't read yaml structs into pipeline operations as usual. A rather big shortcoming. Lots of times I need to filter a list into another list, but this seems impossible with helm:

{{- define "sometpl" -}}
- bla: dibla
- oki: doki
{{- end -}}
---
{{- $v := include "sometpl" . | fromYaml }}
some: {{- $v | toYaml | nindent 2 }}

Will give

some:
  Error: 'error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array
    into Go value of type map[string]interface {}'
-- Morriz
Source: StackOverflow

9/20/2018

Helm defines an include function which is identical to the standard template, except that it returns the rendered output instead of outputting it. You should be able to write

{{- $cassandrafullname := include "cassandra.fullname" . -}}
-- David Maze
Source: StackOverflow