Mv pvc k8s
Jump to navigation
Jump to search
Script
mv-pvc.sh
#!/bin/bash set -eux # Function to display usage instructions usage() { echo "Usage: $0 <old_pvc_name> <new_pvc_name> <new_pvc_size_Gi> <new_storage_class> <namespace>" exit 1 } # Check for correct number of arguments if [ "$#" -ne 5 ]; then usage fi # Assign arguments to variables OLD_PVC_NAME="$1" NEW_PVC_NAME="$2" NEW_PVC_SIZE_GI="$3" NEW_STORAGE_CLASS="$4" NAMESPACE="$5" # Validate PVC size if [[ ! "$NEW_PVC_SIZE_GI" =~ ^[0-9]+$ ]]; then echo "Error: New PVC size must be a positive integer (Gi)" usage fi DATA_COPY_POD_NAME="data-copy-pod" # 1. Create the new PVC kubectl create -f - <<EOF apiVersion: v1 kind: PersistentVolumeClaim metadata: name: $NEW_PVC_NAME namespace: $NAMESPACE spec: accessModes: [ReadWriteOnce] # Or ReadWriteMany if needed resources: requests: storage: ${NEW_PVC_SIZE_GI}Gi storageClassName: $NEW_STORAGE_CLASS EOF # 2. Create the data copy pod kubectl create -f - <<EOF apiVersion: v1 kind: Pod metadata: name: $DATA_COPY_POD_NAME namespace: $NAMESPACE spec: restartPolicy: Never # Important: Only run once containers: - name: data-copy image: alpine:latest command: ["sh", "-c", "apk add --no-cache rsync && rsync -av /mnt/old/ /mnt/new/"] volumeMounts: - name: old-volume mountPath: /mnt/old - name: new-volume mountPath: /mnt/new volumes: - name: old-volume persistentVolumeClaim: claimName: $OLD_PVC_NAME - name: new-volume persistentVolumeClaim: claimName: $NEW_PVC_NAME EOF # 3. Wait for the data copy to finish (adjust timeout as needed) # kubectl wait --for=condition=Succeeded --timeout=5m pod/$DATA_COPY_POD_NAME -n $NAMESPACE kubectl wait --for=condition=Completed --timeout=5m pod/$DATA_COPY_POD_NAME -n $NAMESPACE # 4. Check the status of the copy pod kubectl logs $DATA_COPY_POD_NAME -n $NAMESPACE kubectl get pod $DATA_COPY_POD_NAME -n $NAMESPACE # 5. (Optional) Update your application deployment to use the new PVC # 6. (After verifying everything is working) Delete the data copy pod kubectl delete pod $DATA_COPY_POD_NAME -n $NAMESPACE # 7. Delete the old PVC (after you're *absolutely sure* you don't need it) # kubectl delete pvc $OLD_PVC_NAME -n $NAMESPACE # 8. Delete the old PV (if reclaimPolicy was Retain) # kubectl get pv # Find the PV associated with the old PVC # kubectl delete pv <pv-name>