Skip to content

Instantly share code, notes, and snippets.

@mikamboo
Last active March 28, 2020 00:24
Show Gist options
  • Save mikamboo/8ff4a89f9f57911c599e2ef8b4cbeb8a to your computer and use it in GitHub Desktop.
Save mikamboo/8ff4a89f9f57911c599e2ef8b4cbeb8a to your computer and use it in GitHub Desktop.
Kubernestes copy existing PVC to another

How to Copy existing PVC to another namespace

To achieve this goal we have to :

  1. Create PVC clone (two methods : k8s clone feature or snapshot + restore)
  2. Set reclaim policy for the cloned PV to Retain !
  3. Delete PVC clone (and snapshot if necessary)
  4. Realease the clone PV (set claimRef to null)
  5. Create the new namespace
  6. 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" 

TIPS & TRICKS : Copying kubernetes resources accross namespaces

OLD_NS=my-ns-1
kubectl get rs,secrets -o json --namespace $OLD_NS | jq '.items[].metadata.namespace = "my-ns-2"' | kubectl create-f  -
apiVersion: snapshot.storage.k8s.io/v1alpha1
kind: VolumeSnapshot
metadata:
name: pvc-1-snap
labels:
app: demo-storage
spec:
source:
name: pvc-1
kind: PersistentVolumeClaim
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: pvc-1-clone
labels:
app: demo-storage
spec:
dataSource:
name: pvc-1-snap
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 2Gi # Equal or greater than pvc-1 size
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment