3

I'm trying to iterate over a list in a helm template, and add a suffix to each member. I currently have this block of code that does exactly that:

{{- range $host := .Values.ingress.hosts }}
{{- $subdomain := initial (initial (splitList "." $host)) | join "." }}
{{- $topLevelDomain := last (splitList "." $host) }}
{{- $secondLevelDomain := last (initial (splitList "." $host)) }}
- host: {{- printf " %s-%s.%s.%s" $subdomain $environment $secondLevelDomain $topLevelDomain | trimSuffix "-" }}
{{- end }}

Since I need to do the exact same manipulation twice in the same file, I want to create a new list, called $host-with-env, that will contain the suffix I'm looking for. That way I can only perform this operation once.
Problem is - I've no idea how to create an empty list in helm - so I can't append items from the existing list into the new one.
Any idea how can I achieve this?
I'm also fine with altering the existing list but every manipulation I apply to the list seems to apply to the scope of the foreach I apply to it. Any ideas how to go about this?

edbighead
  • 5,607
  • 5
  • 29
  • 35
Yaron Idan
  • 6,207
  • 5
  • 44
  • 66

1 Answers1

5

It might not be quite clear what result are you trying to achieve, it will be helpful to add your input, like your values.yaml and the desired output. However, I added an example that answers your question.

Inspired by this answer, you can use dictionary.

This code will add suffix to all .Values.ingress.hosts and put them into $hostsWithEnv dictionary into a list, which can be accessed by myhosts key

values.yaml

ingress:
  hosts:
    - one
    - two

configmap.yaml

{{- $hostsWithEnv := dict "myhosts" (list) -}}
{{- range $host := .Values.ingress.hosts -}}
{{- $var := printf "%s.domain.com" $host | append $hostsWithEnv.myhosts | set $hostsWithEnv "myhosts" -}}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
{{- range $hostsWithEnv.myhosts}}
  - host: {{- printf " %s" . | trimSuffix "-" }}
{{- end }}

output

$ helm install --debug --dry-run .              
[debug] Created tunnel using local port: '62742'                                 
...                       
# Source: mychart/templates/configmap.yaml        
apiVersion: v1                                  
kind: ConfigMap                                 
metadata:                                       
  name: my-configmap                            
data:                                           
- host: one.domain.com             
- host: two.domain.com
edbighead
  • 5,607
  • 5
  • 29
  • 35
  • 1
    Thanks! That worked splendidly. You're entirely right it would've been easier to understand my problem if I would give example input/output, I'd keep that in mind for my next questions. – Yaron Idan Jan 05 '19 at 19:54
  • Thank you @edbighead, you saved me after a day of trials!! – Helay Feb 04 '22 at 06:38