Created
July 5, 2021 17:48
-
-
Save invidian/8373c7b02b21e93d5a053cb166b258fd to your computer and use it in GitHub Desktop.
Script to delete context and orphan user and context from kubeconfig
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 | |
if [[ "$#" -ne 1 ]]; then | |
echo "Wrong number of arguments, expected 1, got $#." | |
exit 1 | |
fi | |
CONTEXT_NAME=$1 | |
KUBECONFIG="${KUBECONFIG:-~/.kube/config}" | |
echo "About to remove context '$CONTEXT_NAME' from '$KUBECONFIG'." | |
CONTEXT=$(kubectl config get-contexts $CONTEXT_NAME) | |
if [[ $? -ne 0 ]]; then | |
echo "Failed getting context '$CONTEXT_NAME' from '$KUBECONFIG'." | |
exit 1 | |
fi | |
CONTEXT=$(echo "$CONTEXT" | tail -n1) | |
CONTEXT_CLUSTER=$(echo "$CONTEXT" | awk '{print $3}') | |
CONTEXT_USER=$(echo "$CONTEXT" | awk '{print $4}') | |
CLUSTER_CONTEXTS=$(kubectl config view | yq -r '.contexts[].context.cluster' | grep $CONTEXT_CLUSTER) | |
if [[ $(echo "$CLUSTER_CONTEXTS" | wc -l) -gt 1 ]]; then | |
echo "Cluster '$CONTEXT_CLUSTER' is used in other contexts: '$CLUSTER_CONTEXTS', not removing." | |
else | |
echo "Single use of cluster '$CONTEXT_CLUSTER', removing." | |
kubectl config delete-cluster $CONTEXT_CLUSTER | |
fi | |
USER_CONTEXTS=$(kubectl config view | yq -r '.contexts[].context.user' | grep $CONTEXT_USER) | |
if [[ $(echo "$USER_CONTEXTS" | wc -l) -gt 1 ]]; then | |
echo "User '$USER_CLUSTER' is used in other contexts: '$USER_CONTEXTS', not removing." | |
else | |
echo "Single use of user '$CONTEXT_USER', removing." | |
kubectl config delete-user $CONTEXT_USER | |
fi | |
kubectl config delete-context $CONTEXT_NAME |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment