Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@fbenrejdal

This comment has been minimized.

Copy link

@fbenrejdal fbenrejdal commented Oct 22, 2020

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.

> "$temp_dir/kubernetes-temp.txt"
for context in $(kubectl config view -o jsonpath='{.contexts[*].name}')
do
        echo checking context : $context
        kubectl get pv -o jsonpath='{range .items[*]}{.spec.csi.volumeHandle}{"\t"}{.metadata.name}{"\n"}{end}' --context $context  >> "$temp_dir/kubernetes-temp.txt"
done
sort $temp_dir/kubernetes-temp.txt > $temp_dir/kubernetes.txt

It could include Kubernetes cluster not on vSphere but the probability to have same PV name is zero.
Thanks again
Farid

@bburky

This comment has been minimized.

Copy link
Owner Author

@bburky bburky commented Oct 22, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.