Created
September 23, 2020 19:34
-
-
Save bburky/fd729f129347b9141255fbc2185c52ea to your computer and use it in GitHub Desktop.
Delete any orphaned CNS volumes found in vCenter without a corresponding Kubernetes PV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Delete any orphaned CNS volumes found in vCenter without a corresponding Kubernetes PV. | |
# | |
# Usage: | |
# ./remove-orphaned-cns-volumes.sh | |
# KUBECONFIG=whatever.kubeconfig FORCE=true ./remove-orphaned-cns-volumes.sh | |
set -euo pipefail | |
delete_volume() { | |
echo "Deleting volume: $1" | |
govc volume.rm "$1" | |
} | |
temp_dir=$(mktemp -d) | |
govc volume.ls | sort > "$temp_dir/vcenter.txt" | |
# Retreive the PV list after CNS volumes to avoid race condition: new volumes may appear in this list, but no new volumes should be accidentally deleted. | |
kubectl get pv -o jsonpath='{range .items[*]}{.spec.csi.volumeHandle}{"\t"}{.metadata.name}{"\n"}{end}' | sort > "$temp_dir/kubernetes.txt" | |
orphaned=$(comm -23 "$temp_dir/vcenter.txt" "$temp_dir/kubernetes.txt") | |
rm -rf "$temp_dir" | |
if [ -z "$orphaned" ] | |
then | |
echo "No orphaned CNS volumes found" | |
exit | |
fi | |
echo "Found potentially orphaned CNS volumes:" | |
echo "$orphaned" | |
if [ -z "${FORCE-}" ] | |
then | |
read -p "Delete CNS volumes? [y/N]" -n 1 -r | |
echo | |
if [[ ! $REPLY =~ ^[Yy]$ ]] | |
then | |
exit 1 | |
fi | |
fi | |
# Some careful wordsplitting: split the loop on lines, and then extract the first tab delimeted argument | |
IFS=$'\n' | |
for volume in $orphaned | |
do | |
IFS=$'\t' | |
# shellcheck disable=SC2086 | |
delete_volume $volume | |
done |
I personally don't end up using the contexts feature too often because my clusters have the same admin username and contexts don't work then. For example, deploying multiple identical test clusters, then tearing them down. Instead I specify the KUBECONFIG
environment variable to select the right file.
Anyone seeing this error?
> govc volume.ls
16583672-ef49-4fb7-8153-b1a06b6f0c85 pvc-c485e476-3a96-4736-a646-845bf3075aed
> govc volume.rm pvc-c485e476-3a96-4736-a646-845bf3075aed
govc: ServerFaultCode: Received SOAP response fault from [<cs p:00007f0010029530, TCP:localhost:443>]: retrieveVStorageObject
InvalidArgument: pvc-c485e476-3a96-4736-a646-845bf3075aed is incorrectly formatted.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi @bburky,
thank you very much for your script, it saved me a lot of time.
May I suggest you a modification taking care the possibility to have several K8s clusters hosted on vSphere.
It could include Kubernetes cluster not on vSphere but the probability to have same PV name is zero.
Thanks again
Farid