Skip to content

Instantly share code, notes, and snippets.

@popcornylu
Created August 24, 2019 10:17
Show Gist options
  • Save popcornylu/bff23989e705771712b711acb2840bd8 to your computer and use it in GitHub Desktop.
Save popcornylu/bff23989e705771712b711acb2840bd8 to your computer and use it in GitHub Desktop.
Rename or migrate a PVC from one namespace to another
#!/bin/bash
set -euo pipefail
if [[ $# -ne 2 ]]; then
echo "Usage: kubectl-mvpvc <ns1/pvc1> <ns2/pvc2>"
exit 1
fi
NS_PVC_FROM=$1
NS_PVC_TO=$2
if [[ "$NS_PVC_FROM" =~ ([^/]*)/([^/]*) ]]; then
NS_FROM=${BASH_REMATCH[1]}
PVC_FROM=${BASH_REMATCH[2]}
else
echo "invalid input: ${NS_PVC_FROM}"
exit 1
fi
if [[ "$NS_PVC_TO" =~ ([^/]*)/([^/]*) ]]; then
NS_TO=${BASH_REMATCH[1]}
PVC_TO=${BASH_REMATCH[2]}
else
echo "invalid input: ${NS_PVC_TO}"
exit 1
fi
kubectl -n ${NS_FROM} get pvc "$PVC_FROM" > /dev/null
kubectl get ns "$NS_TO" > /dev/null
if ! kubectl -n "${NS_FROM}" describe pvc "${PVC_FROM}" | grep -q 'Mounted By: <none>'; then
echo "error: pvc is mounted"
exit 1
fi
PVC_BACKUP="${NS_FROM}_${PVC_FROM}.json"
kubectl -n ${NS_FROM} get pvc ${PVC_FROM} -o json > ${PVC_BACKUP}
pv=$(cat ${PVC_BACKUP} | jq -r .spec.volumeName)
echo "pv: ${pv}"
kubectl patch pv "$pv" -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
kubectl -n ${NS_FROM} delete pvc ${PVC_FROM}
kubectl patch pv "$pv" -p '{"spec":{"claimRef":null}}'
cat "${PVC_BACKUP}" | jq ".metadata.name |= \"${PVC_TO}\" | .metadata.namespace |= \"${NS_TO}\"" | kubectl apply -f -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment