美文网首页
configMap中 subPath 和 items 详解

configMap中 subPath 和 items 详解

作者: Rami | 来源:发表于2023-09-13 17:29 被阅读0次

1. subPath字段的作用

在Linux中,将目录A挂载到目录B,则目录B原有的文件都会被目录A下的文件覆盖。
那么在k8s中,如何将configmap挂载到容器中某个目录的文件中呢?答案是使用subPath。
subPath可以将configMap和secret作为文件挂载到容器中而不覆盖挂载目录下的文件。

vim configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: configmap
  namespace: dev
data:
  info: |
    username:admin
    password:123456
  info2: zhangssssssssssssssssssssssssss
vim pod1.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod1
  namespace: dev
spec:
  containers:
  - name: mydocker
    image: zengfeng666/mydocker:1.0
    command: ["/bin/sh", "-c", "while true; do sleep 2; done;"]
    volumeMounts:
    - name: config
      mountPath: /workspace
  volumes:
  - name: config
    configMap:
      name: configmap
vim pod2.yaml
apiVersion: v1
kind: Pod
metadata:
  name: pod2
  namespace: dev
spec:
  containers:
  - name: mydocker
    image: zengfeng666/mydocker:1.0
    command: ["/bin/sh", "-c", "while true; do sleep 2; done;"]
    volumeMounts:
    - name: config
      mountPath: /workspace/info
      subPath: info
    - name: config
      mountPath: /workspace/info2
      subPath: info2
  volumes:
  - name: config
    configMap:
      name: configmap

可以看到,因为pod1中是将configmap直接挂载到了容器的workspace目录,由于Linux的目录挂载特性,原来的workspace目录下的文件将会被挂载过来的目录下(可以将configmap看成一个目录,因为每个key都是一个文件)的文件所覆盖,因此workspace中只有configmap中的info和info2文件。如果不想被覆盖,则要以文件的方式进行挂载,如pod2.yaml中所示,注意mountPath和subPath的写法,subPath此时指的就是configMap中的key,也就是文件名。

image.png image.png

2.items字段的作用

假如不想以key名作为配置文件名可以引入items 字段,在其中逐个指定要用相对路径path替换的key:

     volumes:
      - name: config
        configMap:
          name: configmap
          items:
          - key: info         # 原文件名(key的名称)
            path: userinfo    # 修改之后的文件名(key的名称)
          - key: info2
            path: userinfo2

items还有一个作用,就是只有items下的key对应的文件会被挂载到容器中。
比如pod1.yaml中不想把info和info2都挂载到workspace目录下,而只需要挂载info到workspace目录下,则可以将pod1.yaml的volumes字段修改为:

     volumes:
      - name: config
        configMap:
          name: configmap
          items:
          - key: info         
            path: info     

相关文章

网友评论

      本文标题:configMap中 subPath 和 items 详解

      本文链接:https://www.haomeiwen.com/subject/tsypvdtx.html