Update JSON file placeholder with regex from ConfigMap

3/9/2021

Assuming the following JSON:

{
   "A":{
      "A_KEY":"%PLACEHOLDER_1%",
      "B_KEY":"%PLACEHOLDER_2%"
   }
}

And, the following values.yaml:

placeholders:
  PLACEHOLDER_1: Hello
  PLACEHOLDER_2: World

I would like to load this JSON using Configmap into my pod. But, replace the placeholders with the values under values.yaml automatically based on the key. Thought about writing a simple regex which will search for the words between two % and use this word with .Values.placeholders.$1.

So far, I managed to replace single value using:

apiVersion: v1
kind: ConfigMap
metadata:
  name: config
data:
  config.json: |-
    {{- regexReplaceAll "%PLACEHOLDER_1%" (  .Files.Get "config.json") .Values.placeholders.PLACEHOLDER_1 | nindent 4 }}

The final goal is to replace both PLACEHOLDER_1 and PLACEHOLDER_2 by single regex.

desired JSON:

{
   "A":{
      "A_KEY":"Hello",
      "B_KEY":"World"
   }
}

Any help will be much appriciated.

-- Amit Baranes
kubernetes
kubernetes-helm

1 Answer

3/10/2021

Here is what I have come up with:

apiVersion: v1
kind: ConfigMap
metadata:
  name: config
data:
  config.json: |-
    {{- $file := .Files.Get "config.json" }}
    {{- range $k, $v := .Values.placeholders }}
      {{- $file = regexReplaceAll (printf "%%%s%%" $k) $file  $v }}
    {{- end }}
    {{- print $file | nindent 4 }}

I load a config file content into a $file variable and then iterate over all placeholers.keys from values.yaml file and replace them one by one, saving the output back to the same variable. At the end, $file variable has all fields substituted so I just print it.

-- Matt
Source: StackOverflow