Created
July 23, 2026 13:13
-
-
Save yankcrime/8ccd57dbe791726afa2b49268410070e to your computer and use it in GitHub Desktop.
Teleport Kubernetes cluster selector and kubert wrapper
This file contains hidden or 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
| #!/usr/bin/env bash | |
| set -e | |
| KUBECONFIG_FILE="$HOME/.kube/config" | |
| TCLUSTER=$(tsh status --format=json | jq -r '.active.cluster') | |
| CLUSTER=$(tsh kube ls --format=json | jq -r ' | |
| .[] | |
| | select(.kube_cluster_name != null) | |
| | .order = (if .labels.env == "prod" then 0 elif .labels.env == "uat" then 1 else 2 end) | |
| | "\(.order) [\(.labels.env):\(.labels.region):\(.labels.service)] \(.kube_cluster_name)" | |
| ' | sort -r | cut -d' ' -f2- | fzf --prompt="Choose cluster > ") | |
| if [[ -z "$CLUSTER" ]]; then | |
| echo "No cluster selected." | |
| exit 1 | |
| fi | |
| NAME=$(echo "$CLUSTER" | awk '{print $NF}') | |
| CONTEXT="${TCLUSTER}-${NAME}" | |
| if kubectl config get-contexts -o name --kubeconfig "$KUBECONFIG_FILE" 2>/dev/null | grep -qx "$CONTEXT"; then | |
| echo "β $NAME already registered" | |
| else | |
| echo "π Registering $NAME with Teleport ..." | |
| # tsh kube login writes the context/cluster/user stanzas into $KUBECONFIG_FILE | |
| # *and* sets current-context globally as a side effect. Since every shell shares | |
| # that file, restore whatever was current before so this doesn't leak across | |
| # shells. kubert's isolated per-shell kubeconfig (below) never reads this field. | |
| PREV_CONTEXT=$(kubectl config current-context --kubeconfig "$KUBECONFIG_FILE" 2>/dev/null || true) | |
| tsh kube login "$NAME" >/dev/null | |
| if [[ -n "$PREV_CONTEXT" ]]; then | |
| kubectl config use-context "$PREV_CONTEXT" --kubeconfig "$KUBECONFIG_FILE" >/dev/null | |
| else | |
| kubectl config unset current-context --kubeconfig "$KUBECONFIG_FILE" >/dev/null | |
| fi | |
| fi | |
| echo "π $CONTEXT" | |
| exec kubert ctx "$CONTEXT" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment