2

I've got a simple json config file with the following format:

{
   "applications" : [
       {
           "appName": "app1"
       },
       {
           "appName": "app2"
       }
   ]
}

And right now I've got 2 helm charts defining the deployments for each application:

apiVersion: v1
kind: Deployment
metadata:
  name: app1
# etc, etc, etc
---
apiVersion: v1
kind: Deployment
metadata:
  name: app2
# etc, etc, etc

What I'd like to do is load that json config file at installation time and use it to generate the needed Deployment charts, something like this:

# "config" holds the loaded json file
{{- range .Values.config.applications }}
apiVersion: v1
kind: Deployment
metadata:
  name: {{ .appName | quote }}
{{- end}}

Is this possible? I've tried a lot of the answers around here, but pretty much all of them have to do with passing a json file to the application via a config map. How can I load a json file in helm and use the values in the chart itself? Note that other applications are consuming this file as well, so I can't just change it to a YAML file or something like that.

David Maze
  • 130,717
  • 29
  • 175
  • 215
redsoxfantom
  • 918
  • 1
  • 14
  • 29

2 Answers2

4

Helm has a couple of undocumented functions, including a fromJson function. (Or, if you expect the top-level object to be an array, fromJsonArray.) You should be able to combine this with the file-retrieval calls to be able to do something like:

{{- $config := .Files.Get "config.json" | fromJson }}
{{- range $config.applications }}
name: {{ .appName | quote }}
{{/* and otherwise as you have it in the question */}}
{{- end }}
David Maze
  • 130,717
  • 29
  • 175
  • 215
1

I managed to come up with a workaround.

Thanks to this answer here, I found that python has some neat tricks for going from json to yaml (since json is a subset of yaml). I added a preprocessing step before running the helm install to convert my config.json as follows:

python -c 'import json; import yaml; print(yaml.dump(json.load(open("config.json"))))' > config.yaml

Then I can pass the generated file into helm via the -f config.yaml flag and reference the fields vial the .Values object

redsoxfantom
  • 918
  • 1
  • 14
  • 29
  • 1
    If you're going to do that, you could just use [yq which can convert between json and yaml](https://mikefarah.gitbook.io/yq/usage/convert). Certainly the python oneliner does it but yq is maybe a bit shorter. – ZombieDev Jan 19 '22 at 00:32