Search code examples
kuberneteskubernetes-helmconfigmap

trying to remove first and last square brackets from json injecting data into configmap using helm


I have data in a JSON file and am adding each line as key value into a ConfigMap using Helm, but i need to remove first and last curly brackets.

Below is the JSON file content:

{
    "type": "PurposeResourcesDefinition",
    "version": "1.0",
    "purposeId": "p#####",
    "description": "Artifactory container registry",
    "resources": [{
        "type": "artifactory.containerregistry",
        "name": "<repository name prefixed with the purpose>"
    ]
}

I am using the below Helm syntax:

data:
  {{ range .Files.Lines "foo/app.json" }}
  {{ . }}{{ end }}

How can I remove the surrounding curly brackets using Helm templating?


Solution

  • If you know that { and } will be on lines by themselves, you can just skip them. This isn't especially robust, but it will work for the example you show.

    data:
    {{- range .Files.Lines "foo/app.json" }}
    {{- if and (ne . "{") (ne . "}") }}
      {{ . }}
    {{- end }}
    

    At a higher level, it looks like you're trying to read in a JSON file and then write these values out as the contents of a ConfigMap. Stripping the leading and trailing braces will work because of the syntactic similarities between YAML and JSON, but it might be better to actively convert from one format to the other. Helm has several undocumented conversion functions including fromJson and toYaml. So you can also write this as:

    data: {{- .Files.Get "foo/app.json" | fromJson | toYaml | nindent 2 }}