To achieve this goal we have to :
- Create PVC clone (two methods : k8s clone feature or snapshot + restore)
- Set reclaim policy for the cloned PV to
Retain
! - Delete PVC clone (and snapshot if necessary)
- Realease the clone PV (set
claimRef
to null) - Create the new namespace
- Create a new PVC that meets realesed PV specification (size, matchLabels ...)
Command lines :
# Protect volume for deletion (Tip: create custom StorageClass with this propety as default)
k patch pv pvc-1-clone -p '{"spec": {"persistentVolumeReclaimPolicy": "Retain"}}' --namespace old-ns
# Remove temp volumesnapshot resource
k delete volumesnapshot pvc-1-snap --namespace old-ns
# Remove temp pvc resource : change status to `Released` on the corresponding PV
k delete pvc pvc-1-clone --namespace old-ns
# Make : PV free to be claimed by new PVC : change status to `Available`
k patch pv -p '{"spec": {"claimRef": null}}' --namespace old-ns
k apply -f new-ns-pvc.yaml --namespace new-ns
Exemple PVC resource : new-ns-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: new-ns-pvc
spec:
accessModes:
- ReadWriteOnce
volumeMode: Filesystem
resources:
requests:
storage: 2Gi
# selector: # Useful if PV have label (more accurate)
# matchLabels:
# app: "new-ns-env-app"
OLD_NS=my-ns-1
kubectl get rs,secrets -o json --namespace $OLD_NS | jq '.items[].metadata.namespace = "my-ns-2"' | kubectl create-f -