简体   繁体   中英

Including shell script in ConfigMap using Helm ends in YAML errors

I want to mount a shell script template into a container.

I have the following configmap.yaml :

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "myservice-chart.fullname" . }}--scripts-configmap
  labels:
    app: {{ template "myservice-chart.name" . }}
    chart: {{ template "myservice-chart.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  setup: |
    {{ include "setup" . | indent 4 }}

And this is my setup.tpl :

{{- define "setup" }}
#!/bin/bash
echo "Hello world!"
{{- end }}

When I do a Helm dry-run, Helm generates this (valid) YAML:

...
apiVersion: v1
kind: ConfigMap
metadata:
  name: listening-donkey-myservice-chart-quorum-scripts-configmap
  labels:
    app: myservice-chart
    chart: myservice-chart-0.1.0
    release: listening-donkey
    heritage: Tiller
data:
  setup: |

    #!/bin/bash
    echo "Hello world!"
...

When I run it without --dry-run , it generates this error:

configmap.yaml: error converting YAML to JSON: yaml: line 13: did not find expected key

According to helm chart template guide :

The curly brace syntax of template declarations can be modified with special characters to tell the template engine to chomp whitespace. {{- (with the dash and space added) indicates that whitespace should be chomped left, while -}} means whitespace to the right should be consumed. Be careful! Newlines are whitespace!

So, in order to prevent an useless empty line below setup: | the configmap.yaml should be the following:

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "myservice-chart.fullname" . }}--scripts-configmap
  labels:
    app: {{ template "myservice-chart.name" . }}
    chart: {{ template "myservice-chart.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  setup: |
    {{- include "setup" . | indent 4 }}

It looks like Helm creates a useless empty line below setup: | , hence incorrect indentation.

This is how I fixed it:

...
data:
  setup: |
    # Useless line to prevent "did not find expected key"
    {{ include "setup" . | indent 4 }}

Doing so should be enough, add the '-' sign in the beginning and in the end

data:
setup: |
# Useless line to prevent "did not find expected key"
{{- include "setup" . | indent 4 -}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM