如何从需要模板化的文件目录中生成configmap?

时间:2019-09-10 23:34:18

标签: kubernetes kubernetes-helm

我可以从目录生成ConfigMap,但是它们没有转换模板指令或值。以下是Release.Namespace模板伪指令未在ConfigMap中输出的示例。

.
|____Chart.yaml
|____charts
|____.helmignore
|____templates
| |____my-scripts.yaml
|____values.yaml
|____test-files
  |____test1.txt
---
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: {{ .Release.Namespace }}
data:
  test.txt: |-
{{ .Files.Get "test-files/test1.txt" | indent 4}}
# test-files/test1.txt
test file
{{ .Release.Namespace }}

当我运行helm install . --dry-run --debug --namespace this-should-print时,这就是我得到的与期望的:

实际:

---
# Source: test/templates/my-scripts.yaml
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: test
data:
  test.txt: |-
    # test-files/test1.txt
    test file
    {{ .Release.Namespace }}

预期:

---
# Source: test/templates/my-scripts.yaml
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: test
data:
  test.txt: |-
    # test-files/test1.txt
    test file
    this-should-print

或者,我会对指定目录中的每个文件以如下格式输出感兴趣:

<filename>: |-
  <content>

2 个答案:

答案 0 :(得分:1)

我找到了一种使用tpl函数的方法:

---
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: {{ .Release.Namespace }}
data:
  test.txt: |-
{{ tpl ( .Files.Get "test-files/test1.txt" ) . | indent 4 }}

新输出完全符合预期:

# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: this-should-print
data:
  test.txt: |-
    # test-files/test1.txt
    test file
    this-should-print

要获得奖励积分,可以从目录获取所有文件,而不必在配置映射中更新此列表:

---
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: {{ .Release.Namespace }}
data:
{{ tpl (.Files.Glob "groovy-scripts/*").AsConfig . | indent 4 }}

答案 1 :(得分:0)

.Files.Get将获取这些文件的原始内容并将其转储到生成的YAML中,如果您希望这些文件内容受Helm模板自己渲染,则此方法将行不通。您可以改为创建named templates,然后在其他模板中include

目录结构:tree

.
├── Chart.yaml
├── templates
│   ├── _test1.tpl
│   └── my-scripts.yaml
└── values.yaml

模板:cat templates/my-scripts.yaml

---
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: {{ .Release.Namespace }}
data:
  test.txt: |-
{{- include "mychart.test1" . | indent 4 }}

助手:cat templates/_test1.tpl

{{- define "mychart.test1" }}
test file
{{ .Release.Namespace }}
{{- end }}

结果:helm template . --namespace this-should-print

---
# Source: helm/templates/my-scripts.yaml
---
# templates/myscripts.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-scripts
  namespace: this-should-print
data:
  test.txt: |-
    test file
    this-should-print