如何修改ConfigMap与Secret卷挂载的所属用户及用户组
ConfigMap/Secret卷挂载修改为非root用户所属解决方案
K8s默认对ConfigMap、Secret这类投射类临时卷,不会自动继承Pod级securityContext的fsGroup配置,属于既定的默认行为,你可以根据集群版本选择以下方案解决:
方案1:K8s 1.23及以上版本直接用原生配置
K8s 1.23版本正式GA了fsGroupChangePolicy配置,显式指定为Always即可强制对所有类型的卷(包括ConfigMap、Secret)调整所属用户和组,配置示例如下:
apiVersion: v1 kind: Pod metadata: name: demo-pod spec: securityContext: runAsUser: 1000 # 替换为你的非root用户UID runAsGroup: 2000 # 替换为你的非root用户GID fsGroup: 2000 fsGroupChangePolicy: "Always" # 核心配置,强制调整所有卷权限 containers: - name: business-container image: your-business-image:tag volumeMounts: - name: secret-vol mountPath: /app/secret - name: configmap-vol mountPath: /app/config volumes: - name: secret-vol secret: secretName: your-secret-name - name: configmap-vol configMap: name: your-configmap-name
配置生效后所有挂载卷的所属用户、组都会自动设置为你指定的UID/GID。
方案2:K8s 1.23以下版本用initContainer调整权限
你之前使用initContainer失败大概率是没有给initContainer配置root执行权限,调整后的配置示例如下:
apiVersion: v1 kind: Pod metadata: name: demo-pod spec: securityContext: runAsUser: 1000 runAsGroup: 2000 fsGroup: 2000 initContainers: - name: fix-perm image: busybox:1.36 command: ["sh", "-c", "chown -R 1000:2000 /app/secret /app/config"] securityContext: runAsUser: 0 # 必须显式指定initContainer用root运行才能执行chown volumeMounts: - name: secret-vol mountPath: /app/secret - name: configmap-vol mountPath: /app/config containers: - name: business-container image: your-business-image:tag volumeMounts: - name: secret-vol mountPath: /app/secret - name: configmap-vol mountPath: /app/config volumes: - name: secret-vol secret: secretName: your-secret-name - name: configmap-vol configMap: name: your-configmap-name
注意:K8s默认开启ConfigMap/Secret卷只读特性,仅禁止修改文件内容,修改文件所属用户和组的操作不受影响,可以正常执行。
内容的提问来源于stack exchange,提问作者Nishant Kansal
相关产品推荐
相关产品推荐

