Skip to content

Instantly share code, notes, and snippets.

@pcnoic
Created August 26, 2024 09:01
Show Gist options
  • Save pcnoic/79d24824903a2ae55fce20dd3adb8b8f to your computer and use it in GitHub Desktop.
Save pcnoic/79d24824903a2ae55fce20dd3adb8b8f to your computer and use it in GitHub Desktop.
Generate K8S configs for all GKE clusters under a GCP Project
#!/bin/bash
if ! command -v gcloud &> /dev/null
then
echo "gcloud could not be found. Please install the Google Cloud SDK."
exit 1
fi
if ! command -v kubectl &> /dev/null
then
echo "kubectl could not be found. Please install kubectl."
exit 1
fi
# Ensure the user is authenticated with gcloud
if ! gcloud auth list --filter=status:ACTIVE --format="value(account)" &> /dev/null
then
echo "You are not authenticated with gcloud. Please run 'gcloud auth login' first."
exit 1
fi
PROJECT_ID=$(gcloud config get-value project)
if [ -z "$PROJECT_ID" ]
then
echo "No project ID set. Please set a project ID with 'gcloud config set project PROJECT_ID'"
exit 1
fi
echo "Generating kubeconfigs for GKE clusters in project: $PROJECT_ID"
CLUSTERS=$(gcloud container clusters list --format="value(name,zone)")
if [ -z "$CLUSTERS" ]
then
echo "No GKE clusters found in the project."
exit 0
fi
KUBECONFIG_DIR="./kubeconfigs"
mkdir -p "$KUBECONFIG_DIR"
while IFS= read -r cluster; do
CLUSTER_NAME=$(echo $cluster | cut -d' ' -f1)
CLUSTER_ZONE=$(echo $cluster | cut -d' ' -f2)
echo "Generating kubeconfig for cluster: $CLUSTER_NAME in zone: $CLUSTER_ZONE"
KUBECONFIG_FILE="$KUBECONFIG_DIR/kubeconfig_${CLUSTER_NAME}"
gcloud container clusters get-credentials "$CLUSTER_NAME" --zone "$CLUSTER_ZONE" --project "$PROJECT_ID"
# Save the current context to a separate file
kubectl config view --raw > "$KUBECONFIG_FILE"
echo "Kubeconfig saved to: $KUBECONFIG_FILE"
done <<< "$CLUSTERS"
echo "All kubeconfigs have been generated and saved in the '$KUBECONFIG_DIR' directory."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment