Shared PersistenceVolumeClaim(PVC) across namespaces Shared PersistenceVolumeClaim(PVC) across namespaces kubernetes kubernetes

Shared PersistenceVolumeClaim(PVC) across namespaces


It looks impossible, just because PersistentVolumeClaim is a namespaced object. You can look detailed answer here: https://stackoverflow.com/a/35366775/9065705


If you are using a ReadWriteMany-capable volume (like NFS/EFS), you can create multiple Persistent Volumes (PV) pointing to the same NFS volume, one for each namespace where you want to create a PVC. They can all use the same NFS volume at the same path, or specify different subPath to constrain them to certain directories.


Our solution as follows:

  • First of all,It requires that the persistentVolumeReclaimPolicy of the source PV must be Retain.
  • Secondly, We should add an annotation in the source PVC like that:
pvc-shared-namespaces: NS1, NS2
  • Thirdly, when we want to share PV by the source PVC, we can add two *annotation in the second PVC like that:
pvc-ref: pvc-1  # the name of the source PVCpvc-ref-namespace: pvc-1-ns  # the namespace of the source PVC

Volume create as follows:

CSI takes out pvc-ref and pvc-ref-namespace from CreateVolumeRequest.Parameters in CreateVolume interface:

  1. Find out the source PVC based on pvc-ref and pvc-ref-namespace, take out pvc-shared-namespaces from the source PVC, and judge whether the namespace of the new PVC is in it, if yes, go to 2, otherwise refuse to create;
  2. Determine that the reclaimPolicy of the StorageClass of the new PVC is Retain, if yes, go to 3, otherwise refuse to create;
  3. Find the source PV from the source PVC, and construct a CreateVolumeResponse based on the source PV.

Note: The returned VolumeId is the Spec.CSI.VolumeHandle field of the source PV. After finding the source PV, you can determine whether the persistentVolumeReclaimPolicy of the source PV is Retain. If not, refuse to create.