Search code examples
kubernetespersistent-volumespersistent-volume-claims

Reattach a Dynamically Provisioned PV to a PVC


I deployed a PVC, which dynamically created a PV. After that I deleted the PVC and now my PV looks like below:

PS Kubernetes> kubectl get pv
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS     CLAIM            STORAGECLASS   REASON   AGE
pvc-1b59942c-eb26-4603-b78e-7054d9418da6   2G         RWX            Retain           Released   default/db-pvc   hostpath                26h

When I recreate my PVC, that creates a new PV. Is there a way to reattach the existing PV to my PVC ? Is there a way to do it automatically ?

I tried to attach the PV with my PVC using "volumeName" option, but it did not work.

NAME      STATUS    VOLUME                                    CAPACITY   ACCESS MODES   STORAGECLASS   AGE
db-pvc    Pending   pvc-1b59942c-eb26-4603-b78e-7054d9418da6   0                         hostpath       77s

Solution

  • When a PVC is deleted, the PV stays in the "Released" state with the claimRef uid of the deleted PVC.

    To reuse a PV, you need to delete the claimRef to make it go to the "Available" state

    You may either edit the PV and manually delete the claimRef section, or run the patch command as under:

    kubectl patch pv pvc-1b59942c-eb26-4603-b78e-7054d9418da6 --type json -p '[{"op": "remove", "path": "/spec/claimRef"}]'
    

    Subsequently, you recreate the PVC.