kubernetespersistent-volumespersistent-volume-claims

Mounting kubernetes volume with User permission


I am using Kubernetes yaml to mount a volume. I know I can set the mount folder to be for a specific group using this configuration:

  securityContext:
    fsGroup: 999

but no where I can find a way to also set user ownership and not just the group.

When I access the container folder to check ownership, it is root.

Anyway to do so via kubernetes Yaml? I would expect fsUser: 999 for example, but there is no such thing. :/


Solution

  • There is no way to set the UID using the definition of Pod but you can use an initContainer with the same volumeMount as the main container to set the required permissions.

    It is handy in cases like yours where user ownership needs to be set to a non root value.

    Here is a sample configuration (change it as per your need):

    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