Helm导入文件

1、导入内容到configmap

在mychart文件夹下创建三个文件

1
2
3
echo "message = Hello from config 1" > config1.toml
echo "message = This is config 2" > config2.toml
echo "message = Goodbye from config 3" > config3.toml

在template文件夹下创建configmap

1
2
3
4
5
6
7
8
9
10
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ .Release.Name }}-configmap
data:
{{- $files := .Files }}
{{- range tuple "config1.toml" "config2.toml" "config3.toml" }}
{{ . }}: |-
{{ $files.Get . }}
{{- end }}

验证

1
2
helm lint mychart #测试检查错误
helm template mychart #查看渲染效果

渲染效果输出

1
2
3
4
5
6
7
8
9
10
11
12
13
apiVersion: v1
kind: ConfigMap
metadata:
name: release-name-configmap
data:
config1.toml: |-
message = Hello from config 1

config2.toml: |-
message = This is config 2

config3.toml: |-
message = Goodbye from config 3

整个测试的目录结构

1
2
3
4
5
6
7
8
9
10
11
12
$ tree mychart/
mychart/
├── charts
├── Chart.yaml
├── config1.toml
├── config2.toml
├── config3.toml
├── templates
│ └── configmap.yaml
└── values.yaml

2 directories, 6 files

2、导入内容到Secret

Opaque是一种非常方便的加密方式,对于大量的秘钥内容或者繁琐的符号秘钥,通过Opaque可以进行及其快速便捷的加密解密

1
2
3
4
5
6
7
8
apiVersion: v1
kind: Secret
metadata:
name: {{ .Release.Name }}-secret
type: Opaque
data:
token: |-
{{ .Files.Get "config1.toml" | b64enc }} # 将config1.toml文件中的内容进行加密

加密后的渲染结果

1
2
3
4
5
6
7
8
9
10
# Source: mychart/templates/secretdemo.yaml

apiVersion: v1
kind: Secret
metadata:
name: release-name-secret
type: Opaque
data:
token: |-
bWVzc2FnZSA9IEhlbGxvIGZyb20gY29uZmlnIDEK

3、读取一行数据

1
2
3
4
5
# 以configmap为例

data:
some-file.txt: {{ range .Files.Lines "foo/bar.txt" }}
{{ . }}{{ end }}

4、文件匹配

.Glob返回一个Files类型,因此可以Files返回的对象上调用任何方法。
假如文件目录结构为

1
2
3
4
5
foo/:
foo.txt foo.yaml

bar/:
bar.go bar.conf baz.yaml

通过.Glob进行文件匹配

1
2
3
4
5
6
{{ $currentScope := .}}
{{ range $path, $_ := .Files.Glob "**.yaml" }}
{{- with $currentScope}}
{{ .Files.Get $path }}
{{- end }}
{{ end }}

或者

1
2
3
{{ range $path, $_ :=  .Files.Glob  "**.yaml" }}
{{ $.Files.Get $path }}
{{ end }}

总结

  • 主要使用的是Files.get的功能
  • 读取文件中的一行数据
  • 通过.Glob进行文件匹配