Last active
October 17, 2024 23:35
-
-
Save achetronic/1fb4fa285ab7a7cf83eeed322562252b to your computer and use it in GitHub Desktop.
Get all the GKE contexts available for you authenticted account
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 | |
LOCAL_EXIT_CODE=0 | |
# Get a list of projects from Gcloud | |
PROJECTS=($(gcloud projects list --format="value(projectId)")) | |
# Create a directory to split clusters kubeconfig files later | |
mkdir -p "${HOME}/.kube/clusters" | |
# Loop the projects | |
for PROJECT in "${PROJECTS[@]}"; do | |
echo "Selecting project: ${PROJECT}" | |
gcloud config set project "${PROJECT}" --verbosity=none | |
# Get list of clusters for this project | |
CLUSTERS=($(gcloud container clusters list --project="$PROJECT" --format="csv[separator='@',no-heading](name,zone)")) | |
# Look the clusters' list. Configure contexts | |
for CLUSTER_ZONE in "${CLUSTERS[@]}"; do | |
# Split zone and cluster name | |
CLUSTER=$(echo "${CLUSTER_ZONE}" | cut -d'@' -f1) | |
ZONE=$(echo "${CLUSTER_ZONE}" | cut -d'@' -f2) | |
echo "Cluster found. Adopting its context [ cluster: ${CLUSTER}, zone: ${ZONE} ]" | |
# Configure the context for current cluster | |
export KUBECONFIG="${HOME}/.kube/clusters/${PROJECT}__${ZONE}__${CLUSTER}" | |
gcloud container clusters get-credentials "$CLUSTER" --project="$PROJECT" --zone="$ZONE" || LOCAL_EXIT_CODE=$? | |
#--user-output-enabled --verbosity=debug || LOCAL_EXIT_CODE=$? | |
if [[ "${LOCAL_EXIT_CODE}" -ne 0 ]]; then | |
echo "[···] Context not retrieved. Skipping operation for it."; | |
continue | |
fi | |
done | |
done | |
# Throw an advise | |
printf "Hey, put this on your .bashrc or .zshrc file: \n\n%s" " | |
# [CUSTOM] Show kubectl where to find our kubeconfig files | |
export KUBECONFIG=\$(find ~/.kube/clusters -type f | sed ':a;N;s/\n/:/;ba') | |
" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment