From 2972486a85982fad06be5e579ed2f0e9d22655d9 Mon Sep 17 00:00:00 2001 From: arnie Date: Tue, 29 Jul 2025 10:40:04 +0200 Subject: [PATCH] Add shell script to cleanup aws clusters from kubeconfig --- home-manager/programs/zsh.nix | 9 ++++ .../zsh/aliases/cleanup-kube-config.sh | 53 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100755 home-manager/programs/zsh/aliases/cleanup-kube-config.sh diff --git a/home-manager/programs/zsh.nix b/home-manager/programs/zsh.nix index 6775971..6cc96ff 100644 --- a/home-manager/programs/zsh.nix +++ b/home-manager/programs/zsh.nix @@ -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 diff --git a/home-manager/programs/zsh/aliases/cleanup-kube-config.sh b/home-manager/programs/zsh/aliases/cleanup-kube-config.sh new file mode 100755 index 0000000..376dcc9 --- /dev/null +++ b/home-manager/programs/zsh/aliases/cleanup-kube-config.sh @@ -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