递归地从文件中创建配置映射。

14

我有两个目录中的多个配置文件。例如,

  • conf.d/parentconf1.conf
  • con.d/node1/child1.conf
  • conf.d/node2/child2.conf

我需要使用ConfigMap将这些配置文件以相同的目录结构挂载到Kubernetes Pod中。

尝试使用:

kubectl create configmap --from-file=./conf.d --from-file=./conf.d/node1/child1.conf --from-file=./conf.d/node2/child2.conf. 

配置映射已创建,如预期所料,但无法表达嵌套的目录结构。

是否有可能从文件夹递归创建ConfigMap,并仍然保留文件夹结构在ConfigMap键条目名称中 - 因为意图是将这些ConfigMap挂载到Pod中?

3个回答

13

很遗憾,目前不支持在配置映射中反映目录结构。解决方法是这样表达目录层次结构:

apiVersion: v1
kind: ConfigMap
metadata:
   name: testconfig
data:
  file1: |
    This is file1
  file2: |
    This is file2 in subdir directory
---
apiVersion: v1
kind: Pod
metadata:
  name: testpod
spec:
  restartPolicy: Never
  containers:
    - name: test-container
      image: gcr.io/google_containers/busybox
      command: [ "/bin/sh","-c", "sleep 1000" ]
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        name: testconfig
        items:
        - key: file2
          path: subdir/file2
        - key: file1
          path: file1

这些配置文件是用于logstash的多管道配置文件。因此,已经有10-12个文件(可能会增加)。目前,我使用了一种方法,即使用kubectl将嵌套目录挂载到不同的config-map中。采用这种解决方法。 - nashter
有没有一种方法可以在子目录中挂载一个额外的嵌套文件,但是其余的文件作为第一级挂载?我在子目录中有1个文件和一堆在第一级的文件,所以列出所有文件并不是很方便。 - Albert Bikeev

10
一个可自动化的解决方法:压缩您的文件,将 tar 配置映射到 /tmp 目录下的 configmap 卷文件中,在容器开始时进行解压。
创建 tar:
tar -cvf conf-d.tar ./conf.d
kubectl create configmap conf-d --from-file=conf-d.tar
rm conf-d.tar

在你的pod.yml文件中,在你的命令或默认镜像命令之前添加tar -xf:

    command: [ "/bin/sh","-c", "tar -xf /tmp/conf-d.tar -C /etc/ && sleep 1000" ]
    volumeMounts:
      - mountPath: /tmp/conf-d.tar
        name: nginx-config-volume
        subPath: conf-d.tar

5
在编写 Helm charts 的模板时,可以使用 内置工具 创建一个配置映射或包含目录中所有文件的密钥。
目录结构:
test
├── bar
│   └── init.sh
├── foo
│   ├── some.sh
│   └── thing.sh
└── README

Helm配置映射模板:
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  {{- $files := .Files }}
  {{- range $path, $_ := .Files.Glob "test/**" }}
  {{ $path | replace "/" "." }}: |
{{ $files.Get $path | indent 4 }}
  {{- end }}

结果:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  test.bar.init.sh: |
    echo foo
  test.foo.some.sh: |
    echo foo
  test.foo.thing.sh: |
    echo foo
  test.README: |
    # My title

使用 Helm 3.7.1 进行测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接