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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anyone seeing this error?