首页 > 解决方案 > 如何将用户凭据传递到 Kubernetes Pod 内的(用户受限的)挂载卷?

问题描述

我正在尝试通过 Kubernetes 机密将用户凭据传递到 Kubernetes Pod 内已安装的、受密码保护的目录。NFS 文件夹/mount/protected有用户访问限制,即只有某些用户可以访问该文件夹。

这是我的 Pod 配置:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  volumes:
  - name: my-volume
    hostPath:
      path: /mount/protected
      type: Directory
    secret:
      secretName: my-secret
  containers:
  - name: my-container
    image: <...>
    command: ["/bin/sh"]
    args: ["-c", "python /my-volume/test.py"]
    volumeMounts:
    - name: my-volume
      mountPath: /my-volume

应用它时,我收到以下错误:

The Pod "my-pod" is invalid:
* spec.volumes[0].secret: Forbidden: may not specify more than 1 volume type
* spec.containers[0].volumeMounts[0].name: Not found: "my-volume"

我根据以下指南创建了 my-secret:
https
://kubernetes.io/docs/tasks/inject-data-application/distribute-credentials-secure/#create-a-secret 所以基本上:

apiVersion: v1
kind: Secret
metadata:
  name: my-secret
data:
  username: bXktYXBw
  password: PHJlZGFjdGVkPg==

但是当我安装文件夹/mount/protected时:

spec:
  volumes:
  - name: my-volume
    hostPath:
      path: /mount/protected
      type: Directory

python: can't open file '/my-volume/test.py': [Errno 13] Permission denied运行挂载此卷路径的 Pod 时出现权限被拒绝错误。

我的问题是如何告诉我的 Pod 它应该使用特定的用户凭据来访问这个挂载的文件夹?

标签: kuberneteskubernetes-secrets

解决方案


您试图告诉 Kubernetes应该my-volume主机路径和 Secret 中获取其内容,并且它只能拥有其中一个。

您无需手动指定主机路径。Kubernetes 会找到适合放置 Secret 内容的位置,并且它仍然会在mountPath您指定的容器中可见。(完全指定hostPath:通常是错误的,除非您可以保证该路径将与您期望的内容存在于集群中的每个节点上。)

所以改变:

volumes:
- name: my-volume
  secret:
    secretName: my-secret
  # but no hostPath

推荐阅读