Lorenzo's blog

Technical reference about work stuff

Cloning Kubernetes Persistent Volumes to another namespace

🗓️ Date: 2022-11-13 · 🗺️ Word count: 382 · ⏱️ Reading time: 2 Minute

Creating a copy of a PV can be useful to debug and modify its data while the original PV remains unaffected.

Two use-cases for cloning a PV can be:

  • creating a copy in another namespace
  • replacing the content of a PVC with data from another namespace

This guide covers both cases. It also assumes velero is already installed and configured.

Creating a copy in another namespace

  1. Assign a label to the PVC and PV, editing the kubernetes resources: For instance:
labels:
    tobackup: "true"
  1. Create the backup of the PVC and PV:
velero backup create backup-name \
    --include-cluster-resources=true \ # necessary to backup PVs
    --include-namespaces source-namespace \
    --volume-snapshot-locations default \ # usually not required
    --include-resources persistentvolumeclaims,persistentvolumes \
    --selector tobackup="true"
  1. Restore the backup on the destionation namespace:

The velero documentation specifies that, when using the --namespace-mappings flag, the reference to the PVC inside the PV will be modified to the new (destionation) namespace.

Furthermore, the name of the PV will be changed (creating a clone of the original PV) because both these conditions are met:

  • The PV already exists on the target cluster.
  • The PV’s claim namespace has been remapped.
velero restore create restore-name \
    --from-backup backup-name \
    --include-resources persistentvolumeclaims,persistentvolumes \
    --namespace-mappings source-ns:destionation-ns

The result will be:

  • a PVC with the original name in the destination namespace
  • a cloned PV referencing the new PVC

Replacing the content of a PVC with data from another namespace

Tf we want to replace the content of a PVC (and PV) in a namespace with the content of a PVC in another one, the method described above is not enough. That is because a old PVC will not be replaced by the cloned one, unless it has the same name. The replacement can be useful to replicate the data of an environment to another one.

Fortunately, removing the old PVC and fixing the references between PVs and PVCs is straightforward.

  1. Scale down the deployment attached to the PVC.
  2. Make sure the reclaim policy of the PVC is on “Retain”, if not change it.
  3. Delete the PVCs in the destionation namespace, both the previous one and the one just cloned.
  4. Edit the cloned PV replacing the PVC name with the one of the PVC the pods expects.
  5. Scale up the deployment, now it should pick up the cloned PV.