dotfiles/home/.bin/kube-force-delete
Marcus Noble 951bbcc7fd
Handle non-namespaced resouces
Signed-off-by: Marcus Noble <github@marcusnoble.co.uk>
2024-06-07 13:18:56 +01:00

90 lines
2.3 KiB
Bash
Executable File

#!/usr/bin/env bash
source .utils
NAMESPACE="$(kubectl config view --minify --output 'jsonpath={..namespace}' &>/dev/null)"
set -e
NAMESPACE=${NAMESPACE:-default}
SELECTOR=""
print_usage() {
blue "kube-force-delete - Force delete resources, even those with finalizers"
echo " "
underline "Usage:"
echo "kube-force-delete [RESOURCE_TYPE] [RESOURCE_NAME]"
echo " "
underline "Options:"
echo "-h, --help show this help text"
echo "-n, --namespace the namespace the resource is in (default: current namespace)"
}
POS_ARGS=()
while test $# -gt 0; do
case "$1" in
-n|--namespace)
shift
NAMESPACE=$1
shift
;;
-l|--selector)
shift
SELECTOR="$1"
shift
;;
-h|--help)
print_usage
exit 0
;;
/)
# We want to ignore slash seperators between resource types and names
shift
;;
*)
POS_ARGS+=(`echo $1 | tr '/' ' '`)
shift
;;
esac
done
if [ ${#POS_ARGS[@]} -lt 2 ] && [[ "${SELECTOR}" == "" ]]; then
echo "Please provide the resource type and name to delete"
exit 1
fi
function deleteResource() {
RES="${1//.v1/}"
echo "Deleting ${RES}"
kubectl patch -p '{"metadata":{"finalizers":null}}' --type=merge -n ${NAMESPACE} ${RES} 1>/dev/null|| printf ""
kubectl delete -n ${NAMESPACE} ${RES} 2>/dev/null || printf ""
}
printf "⚠️ This could leave cloud resources undeleted if finalizers aren't honoured ⚠️\n\n"
RESOURCES=()
if [[ "${SELECTOR}" == "" ]]; then
printf "Are you sure you want to delete ${POS_ARGS[0]}/${POS_ARGS[1]}? (y/n): "
RESOURCES=("${POS_ARGS[0]}/${POS_ARGS[1]}")
else
printf "Are you sure you want to delete all matching '${SELECTOR}'? (y/n): "
SELECTOR="-l ${SELECTOR}"
NAMES="$(kubectl api-resources --verbs list -o name 2>/dev/null | tr '\n' ,)"
RESOURCES=$(kubectl get "${NAMES::${#NAMES}-1}" --ignore-not-found ${SELECTOR} -n ${NAMESPACE} -o go-template='{{range.items}}{{.kind}}.{{.apiVersion}}/{{.metadata.name}}{{"\n"}}{{end}}' 2>/dev/null | tr '[:upper:]' '[:lower:]' | sed -r "s|/(v.+)/|/|g")
fi
read CONFIRM
if [ "${CONFIRM}" = "y" ]; then
echo ""
echo "💣 OK, I hope you know what you're doing..."
IFS='
'
for RESOURCE in ${RESOURCES}
do
deleteResource ${RESOURCE}
done
else
echo "Aborting..."
exit 1
fi