Unable to write file. Volume mounted as root

3/29/2019

I am spinning up a Pod (comes up with Non Root user) that needs to write data to a volume. The volume comes from a PVC.

The pod definition is simple

kind: Pod
apiVersion: v1
metadata:
  name: task-pv-pod
spec:
  volumes:
    - name: task-pv-storage
      persistentVolumeClaim:
       claimName: test-pvc
  containers:
    - name: task-pv-container
      image: jnlp/jenkins-slave:latest
      command: ["/bin/bash"]
      args: ["-c", "sleep 500"]
      ports:
        - containerPort: 80
          name: "http-server"
      volumeMounts:
        - mountPath: "/usr/share/nginx/html"
          name: task-pv-storage

When I exec into the Pod and try to write into /usr/share/nginx/html

I get

jenkins@task-pv-pod:/usr/share/nginx/html$ touch test
touch: cannot touch ‘test’: Permission denied

Looking at the permissions of the directory

jenkins@task-pv-pod:~$ ls -ld /usr/share/nginx/html
drwxr-xr-x 3 root root 4096 Mar 29 15:52 /usr/share/nginx/html

Its clear that ONLY root user can write to /usr/share/nginx/html but thats not what I want.

Is there a way to change the permissions for mounted volumes ?

--
kubernetes
kubernetes-pvc

2 Answers

3/29/2019

You can consider using an initContainer to mount your volume and change permissions. The initContainer will be run before the main container(s) start up. The usual pattern for this usage is to have a busybox image (~22 MB) to mount the volume and run a chown or chmod on the directory. When your pod's primary container runs, the volume(s) will have the correct ownership/access privileges.

Alternatively, you can consider using the initContainer to inject the proper files as shown in this example.

Hope this helps!

-- Frank Yucheng Gu
Source: StackOverflow

3/30/2019

A security context defines privilege and access control settings for a Pod or Container. Just try securityContext:

kind: Pod
apiVersion: v1
metadata:
  name: task-pv-pod
spec:
  securityContext:
    fsGroup: $jenkins_uid
  volumes:
    - name: task-pv-storage
      persistentVolumeClaim:
       claimName: test-pvc
...
-- S.J
Source: StackOverflow