How to reattach a PVC to an existing PV or migrate PVC from one namespace to another in Kubernetes/Openshift cluster

I have been advising many users on various channels ( mail, slack..etc) on how to accomplish PVC migration or reattaching an existing PV to a new PVC for various use cases in the past. That said, the use cases involve scenarios like if the user wants to attach a new PVC to an older/existing PV or it could be that someone wants to migrate a PVC from one namespace to another. But, this hack/workaround always remained out of support contract and helped folks who wanted to achieve the end result in some manner, so keep it in mind before you attempt this.

The PVC PV binding always appears that a 1:1 mapping and at times users want to attach an existing PV to a new PVC which could be in another namespace.

Lets start: As you know, a bound PVC has a `reclaimPolicy` which is default to “delete”. If the PV which you want to attach to a new PVC is of “delete” policy you need to edit the PV spec and mark reclaimPolicy as “Retain”.

[terminal]
“persistentVolumeReclaimPolicy”: “Retain”,
[/terminal]
Before you begin all of this process, lets backup an existing PVC yaml/json:

[terminal]
oc get pvc -o yaml > backup_pvc.yaml [/terminal]

As for any hacks on storage, I would recommend to backup the data on the volume which is mapped to PV. Data is critical always! so based on your criticality, back up it from the storage backend. The storage backend could be any and in my case it is GlusterFS.

Once the data is backed up, let’s delete the original PVC.

[terminal]
kubectl delete pvc pvcname
[/terminal]
When you delete the PVC, the PV state should move along. It should soon transitioned to `Released` State. Wait for the PVC status to reflect “Released” and once its on “Released” state, edit the PV and delete `claimRef` field from PV spec/definition, which refers to now-deleted PVC.

Extract or fetch and keep the PV name for the future. We need that for the new PVC. Once we have it, create a new PVC in the desired namespace that refers to the `volumeName` field to the old PV name.

For example:

[terminal]
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: newclaim
spec:
accessModes:
– ReadWriteMany
resources:
requests:
storage: 5Gi
storageClassName: glusterfs
volumeMode: Filesystem
volumeName: pvc-3466cff4-g4gb-12e9-962b-54009bg11116
[/terminal]

The new PVC should bind to existing PV and volume should become available in new namespace.!!

Digiprove sealCopyright secured by Digiprove © 2020 Humble Chirammal