kubernetes-helmgo-templatessprig-template-functions

Example of merge operation in helm


In offcial documentaion the description is very poor:

Merge two or more dictionaries into one, giving precedence to the dest dictionary:

$newdict := merge $dest $source1 $source2 This is a deep merge operation but not a deep copy operation. Nested objects that are merged are the same instance on both dicts. If you want a deep copy along with the merge, then use the deepCopy function along with merging...

Could you please provide example with input and output values ?


Solution

  • Consider we have 3 maps (or Dict) as follows:

    dst = {
        "default": "default",
        "overwrite": "me",
        "key": "true"
    }
    src1 = {
        "overwrite": "overwritten",
        "key": "false",
        "name": "value1"
    }
    src2 = {
        "key": "false",
        "name": "value2"
    }
    

    You can represent it in helm with:

    {{ $dst := dict "default" "default" "overwrite" "me" "key" "true"}}
    {{ $src1 := dict "overwrite" "overwritten" "key" "false" "name" "value1"}}
    {{ $src2 := dict  "key" "false" "name" "value2"}}
    

    Merge

    In merging dicts, keys with different values will be kept, and in the same keys cases, dst dict takes precedence. For example, result of merge $dst $src1 $src2 would be:

    mergedDict = {
        "default": "default",
        "key": "true",
        "name": "value1",
        "overwrite": "me"
    }
    

    or in helm syntacs:

    {{ $mergedDict := merge $dst $src1 $src2 }}
    

    would be:

    mergedDict: map[default:default key:true name:value1 overwrite:me]
    

    mergeOverwrite

    In mergeOverwrite, precedence would be from right to left. So we have:

    {{ $mergedDict := mergeOverwrite  $dst $src1 $src2}}
    

    would be:

    mergedDict: map[default:default key:false name:value2 overwrite:overwritten]
    

    or

    {
        "default": "default",
        "key": "false",
        "name": "value2",
        "overwrite": "overwritten"
    }