Search code examples
jsontemplatesrangekubernetes-helm

helm template iterate over json list


I have a input file which has content like below:

snmpv3:      
  notificationTargetsConfiguration: '[{"manager_ip": "10.32.234.31", "username": "initial_snm1",
    "trap_dst_port": ""}, {"manager_ip": "10.32.234.42", "username": "initial_snm",
    "trap_dst_port": ""}, {"manager_ip": "10.32.232.24", "username": "initial_snm1",
    "trap_dst_port": ""}, {"manager_ip": "10.32.234.18", "username": "initial_snm",
    "trap_dst_port": ""}]'
  userConfiguration: '[{"auth_passwd": "U2FsdGVkX1+OhUYQwCqWgKE4TrGQCD5MoT1YrcCBqKU=",
    "auth_protocol": "MD5", "passphrase": "test", "priv_passwd": "U2FsdGVkX1+OhUYQwCqWgKE4TrGQCD5MoT1YrcCBqKU=",
    "priv_protocol": "DES", "sec_level": "authPriv", "username": "initial_snm"}, {"auth_passwd":
    "U2FsdGVkX1+OhUYQwCqWgKE4TrGQCD5MoT1YrcCBqKU=", "auth_protocol": "MD5", "passphrase":
    "test", "priv_passwd": "U2FsdGVkX1+OhUYQwCqWgKE4TrGQCD5MoT1YrcCBqKU=", "priv_protocol":
    "DES", "sec_level": "authPriv", "username": "initial_snm1"}]'
  myData: {"manager_ip": "10.32.234.42", "username": "initial_snm", "trap_dst_port": ""}

Now using {{- range $key, $value := $.Values.snmpv3.myData }} I am able to iterate but when using range over userConfiguration or notificationTargetsConfiguration it is just not working.

Since myData is just a single json, I can get key and value, but other are json list. I am not able to loop over a list.

tried: {{- range $myrow := $Values.snmpv3.notificationTargetsConfiguration }} {{- range $key, $value := $myrow -}}

but this is simply not working.


Solution

  • I spent hours figuring out the solution. Finally, I got the answer but before that list of challenges here.

    1. The JSON data is inside the single quote, which means for parser it is a string, not JSON or dictionary.
    2. The JSON data is a list of dictionaries.

    Solution:

    1. First we need to extract each JSON list item in some variable.
    2. Loop over the variable which should become a list of dictionaries.
    3. extract data from each dictionary.

    thus final code will look like something like this:

    {{- $userConfig := (printf "{ userConfig: %s }" $.Values.snmpV3.userConfiguration) | fromYaml -}}
    
    {{- range $uconfig := get $userConfig "userConfig" -}}
      userName: {{ $uconfig.username }}