How to get 2 structure from values and create JSON in Helm?

1/28/2021

Values

a :
  b:c
  d:e
  f: 
    g:h

I have config map

apiVersion: v1
kind: ConfigMap
metadata:
  name: myName
  labels:
data:
  myDaya.cfg: |-
    {{ toJson .Values.a }} 

The result is

myDaya.cfg: {"b":"c", "d","e", "f":{"g":"h"}}}

Now I added another values to .values file

a1:
  b1:
    c1: d1

The "a1" must be in different structure
The new .Values

a :
  b:c
  c:d
  e: 
    f:g
**a1:
  b1:
    c1: d1**

The new config now should include 1 json also with value a1 meaning

myDaya.cfg: {"a": { "b":"c", "d","e", "f":{"g":"h"}} ,"b1:{"c1":"d1"}}

Could you advise me how I can change the config map ?

-- user1365697
kubernetes
kubernetes-helm

1 Answer

1/28/2021

Helm has several functions for manipulating dictionary objects (which come from the Sprig template support library). These include a merge function that combines multiple dictionaries into one.

The one trick with the dictionary functions is that they generally work by mutating an existing dictionary object. This is in contrast to most of the other Helm/Sprig functions, which act on immutable objects. So to use merge without accidentally changing .Values, you need to create a new empty dictionary (with dict and then merge the various sub-dictionaries into it.

<!-- language: lang-yaml -->
data:
  myDaya.cfg: |-
{{ merge dict .Values.a .Values.a1 | toJson | indent 4 }}

Or, if you want to keep the top-level dictionary keys, you can use dict to directly construct the result dictionary:

<!-- language: lang-none -->
{{ dict "a" .Values.a "a1" .Values.a1 | toJson | indent 4 }}
-- David Maze
Source: StackOverflow