使用Helm在ConfigMap中嵌入Shell脚本时出现YAML错误
Looks like you ran into a classic Helm indentation gotcha! That YAML-to-JSON error is happening because the way you're using the indent function is creating invalid whitespace in your ConfigMap's script content.
Let me break down the problem:
- In your
configmap.yaml, you're using{{ include "setup" . | indent 4 }}under thesetup: |block. - The
indent 4function adds 4 spaces to every line of the included template output—including the first line#!/bin/bash. - But you already have 4 spaces of indentation after the
setup: |line. This means the first line of your script ends up with 8 spaces total, which confuses the YAML parser (it expects consistent indentation for the block content).
The Fix
Swap out indent 4 for nindent 4. The nindent function is designed exactly for this scenario: it first adds a newline, then applies the specified indentation to every line of the input. This ensures your script content has the correct, consistent indentation relative to the YAML block.
Here's your updated 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" . | nindent 4 }}
Why This Works
When Helm renders this, the nindent 4 will generate the script content with exactly 4 spaces of indentation per line, matching the context of the setup: | block. The YAML parser will recognize this as valid block literal content, and your ConfigMap will be created without errors.
As a quick rule of thumb: use nindent when you're inserting multi-line content into a YAML block that already has a line break and base indentation. Use indent only when you need to adjust the indentation of content that doesn't already have a leading newline matching the YAML structure.
内容的提问来源于stack exchange,提问作者mitchkman

