this repo has no description
1#!/bin/bash
2
3# Requires kubectl all set up already
4# Requires source and destination Namespaces exist already
5
6# Approach taken from https://stackoverflow.com/a/66078690/920350
7
8if [ "$#" -ne 3 ]; then
9 echo "ERROR: invalid arguments"
10 echo ""
11 echo "Usage: $0 SRCNS DESTNS PVC"
12 echo " SRCNS: namespace where PVC currently exists"
13 echo " DESTNS: namespace where PVC shall exist"
14 echo " PVC: persistentVolumeClaim name"
15 exit 1
16fi
17
18SRCNS="$1" # e.g. default
19DESTNS="$2" # e.g. media
20PVC="$3" # e.g. plex-config
21
22#####################################################
23PV=$(kubectl -n "$SRCNS" get pvc "$PVC" -o custom-columns=PV:.spec.volumeName --no-headers)
24
25if [ "$PV" == "" ]; then
26 echo "ERROR: No PV found for PVC \"$PVC\" in namespace \"$SRCNS\". Exiting."
27 exit 1
28fi
29
30kubectl get ns "$DESTNS" &> /dev/null
31if [ "$?" -ne 0 ]; then
32 echo "ERROR: Destination namespace \"$DESTNS\" not found. Exiting."
33 exit 1
34fi
35
36echo "Plan Summary"
37echo ""
38echo "PVC to move: \"$PVC\""
39echo " PV: \"$PV\""
40echo " from NS: \"$SRCNS\""
41echo " to NS: \"$DESTNS\""
42
43echo ""
44read -r -p "Are you sure? [y/N] " response
45if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
46then
47 # Store the current yaml for later
48 TEMPPVC=$(mktemp)
49 TEMPPV=$(mktemp)
50 kubectl get pvc -n "$SRCNS" "$PVC" -o yaml > "$TEMPPVC"
51 kubectl get pv "$PV" -o yaml > "$TEMPPV"
52
53 # Patch the pv to be Retain on delete, in case it is currently set to something else
54 kubectl patch pv "$PV" -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'
55 sleep 1
56
57 # Check if that worked
58 RETAIN=$(kubectl get pv "$PV" -o custom-columns=Reclaim:.spec.persistentVolumeReclaimPolicy --no-headers)
59 if [ "$RETAIN" != "Retain" ]; then
60 echo "ERROR: Reclaim policy didn't change to Retain, exiting. Check the PV."
61 exit 1
62 fi
63 echo "Changed reclaim policy on $PV to Retain"
64 sleep 1
65
66 # Delete the original PVC
67 echo "Deleting original PVC from \"$SRCNS\" (don't panic)..."
68 kubectl delete -n "$SRCNS" pvc "$PVC"
69 sleep 0.5
70
71 # Patch the PV's reference to the PVC to get rid of uid
72 echo "Disconnecting PV from PVC..."
73 kubectl patch pv "$PV" -p "{\"spec\":{\"claimRef\":{\"namespace\":\"$DESTNS\",\"name\":\"$PVC\",\"uid\":null}}}"
74 sleep 0.5
75
76 # Create the new PVC
77 echo "Creating new PVC..."
78 grep -v -e "uid:" -e "resourceVersion:" -e "namespace:" -e "selfLink:" "$TEMPPVC" | kubectl -n "$DESTNS" apply -f -
79 sleep 5
80
81 # Get the new PVC's uid
82 PVCUID=$(kubectl get -n "$DESTNS" pvc "$PVC" -o custom-columns=UID:.metadata.uid --no-headers)
83
84 # Patch the PV with the new PVC's uid
85 echo "Linking PV to new PVC..."
86 kubectl patch pv "$PV" -p "{\"spec\":{\"claimRef\":{\"uid\":\"$PVCUID\",\"name\":null}}}"
87else
88 exit 1
89fi