Search code examples
kubernetes-helm

How to create a k8s configmap by looping over nested helm values


The helm values look like in the following example. Here appdata can scale to any number but will contain the same set of keys.

data:
  appdata:
    config0:
      url: 'https://example1.com'
      port: '80'
    config1:
      url: 'https://example2.com'
      port: '8673'
    someotherconfig:
      url: 'https://example3.com'
      port: '9887'
    ...
    ...

This is what I have so far. This keeps updating the last config's data from someotherconfig key and also I want to have the config map name to contain the config name for each iteration, like {{ template "app" $ }}-config0, {{ template "app" $ }}-config1 and so on based on iteration.

{{- range $Mydata := $.Values.data.appdata }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "app" $ }}
  labels:
data:
  url: {{ $Mydata.url }}
  port: {{ $Mydata.port }}
{{- end }}

Solution

  • You're almost there. You need to use the key/value notation to get the key name. Try the following.

    {{- range $configuration, $Mydata := $.Values.data.appdata }}
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: {{ template "app" $ }}-{{ $configuration }}
    data:
      url: {{ $Mydata.url }}
      port: {{ $Mydata.port }}
    {{- end }}