Add shell script to cleanup aws clusters from kubeconfig

This commit is contained in:
Arnie 2025-07-29 10:40:04 +02:00
parent 409a96c224
commit 2972486a85
No known key found for this signature in database
GPG Key ID: 4BDFA3BCF2999D11
2 changed files with 62 additions and 0 deletions

View File

@ -92,6 +92,15 @@ in
git-sync-remote = lib.mkDefault "git remote update origin --prune";
cleanup-kube-config = "${pkgs.writeShellApplication {
name = "app";
text = ./zsh/aliases/cleanup-kube-config.sh;
runtimeInputs = [
pkgs.gnugrep
pkgs.coreutils
];
}}/bin/app";
klogs = lib.mkDefault "${pkgs.writeShellScript "klogs" ''
ctx="$1"
shift

View File

@ -0,0 +1,53 @@
set -e
declare -A account_clusters
declare -A account_profiles
for ctx in $(kubectl config get-contexts -o name); do
if [[ "${ctx:0:7}" != "arn:aws" ]]; then
continue
fi
account_id="${ctx#*:*:*:*:}"
account_id="${account_id%%:*}"
cluster_name="${ctx#*cluster/}"
if [[ "${account_id}" == "" ]] || [[ "${cluster_name}" == "" ]]; then
continue
fi
if [[ ! -v account_profiles[$account_id] ]]; then
aws_profile=$(grep "sso_account_id = $account_id" ~/.aws/config -B 5 | grep "\[profile" | tail -n 1 | tr -d '[]')
aws_profile="${aws_profile#profile }"
if [[ "${aws_profile}" == "" ]]; then
continue
fi
account_profiles[$account_id]=$aws_profile
account_clusters[$account_id]=""
fi
account_clusters[$account_id]+="$cluster_name "
done
for acc in ${!account_profiles[@]}; do
profile=${account_profiles[$acc]}
declare -A current_clusters
for remote_cluster in $(aws --profile $profile eks list-clusters --query "clusters" --output text); do
current_clusters[$remote_cluster]=""
done
for cluster in ${account_clusters[$acc]}; do
if [[ -v current_clusters[$cluster] ]]; then
# check if credentials are current
echo "$cluster cluster exists"
else
kubectl config delete-context "$(kubectl config get-contexts -o name | grep "$acc:cluster/$cluster" | head -n 1)"
fi
done
unset -v current_clusters
done