使用用户权限挂载 kubernetes 卷

时间:2021-03-29 16:13:52

标签: kubernetes persistent-volumes persistent-volume-claims

我正在使用 Kubernetes yaml 挂载一个卷。 我知道我可以使用此配置将挂载文件夹设置为特定组:

  securityContext:
    fsGroup: 999

但我找不到一种方法来设置用户所有权,而不仅仅是组。

当我访问容器文件夹以检查所有权时,它是根。

无论如何要通过 kubernetes Yaml 做到这一点? 例如,我希望 fsUser: 999 ,但没有这样的东西。 :/

2 个答案:

答案 0 :(得分:3)

无法使用 Pod 的定义来设置 UID,但您可以使用与主容器具有相同 initContainervolumeMount 来设置所需的权限。

在像您这样需要将用户所有权设置为非根值的情况下,它很方便。

这是一个示例配置(根据您的需要进行更改):

apiVersion: v1
kind: Pod
metadata:
  name: security-context-demo
spec:
  volumes:
  - name: sec-ctx-vol
    emptyDir: {}
  containers:
  - name: sec-ctx-demo
    image: busybox
    command: [ "sh", "-c", "sleep 1h" ]
    volumeMounts:
    - name: sec-ctx-vol
      mountPath: /data/demo
    securityContext:
      allowPrivilegeEscalation: false
  initContainers:
  - name: volume-mount-hack
    image: busybox
    command: ["sh", "-c", "chown -R 999:999 /data/demo"]
    volumeMounts:
    - name: sec-ctx-vol
      mountPath: /data/demo

Permissions would end up looking like this

答案 1 :(得分:1)

不,没有这样的选择。要检查 securityContext 中可用的每个选项,您可以使用

kubectl explain deployment.spec.template.spec.securityContext

根据文档

   fsGroup      <integer>
     A special supplemental group that applies to all containers in a pod. Some
     volume types allow the Kubelet to change the ownership of that volume to be
     owned by the pod: 1. The owning GID will be the FSGroup 2. The setgid bit
     is set (new files created in the volume will be owned by FSGroup) 3. The
     permission bits are OR'd with rw-rw---- If unset, the Kubelet will not
     modify the ownership and permissions of any volume.

通过组所有权处理对文件的访问通常是个好主意,因为在受限的 kubernetes 配置中,您实际上无法控制用户 ID 或组 ID,例如在 RedHat Openshift 中。

如果您的 kubernetes 提供商允许,您可以使用 runAsUser

   runAsUser    <integer>
     The UID to run the entrypoint of the container process. Defaults to user
     specified in image metadata if unspecified. May also be set in
     SecurityContext. If set in both SecurityContext and PodSecurityContext, the
     value specified in SecurityContext takes precedence for that container.

您的应用程序将使用您想要的 uid,并且自然会根据您的需要创建和访问文件。如前所述,这样做通常不是最好的主意,因为它会使您的应用程序在不同平台上的分发变得更加困难。