Skip to content

Instantly share code, notes, and snippets.

@bburky
Created September 23, 2020 19:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bburky/fd729f129347b9141255fbc2185c52ea to your computer and use it in GitHub Desktop.
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
#!/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
@2stacks
Copy link

2stacks commented Aug 16, 2021

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