Skip to content

Instantly share code, notes, and snippets.

@sldenazis
Created January 31, 2025 12:52
Show Gist options
  • Save sldenazis/ba0a2b4ee6e8e413e052f1818c823c57 to your computer and use it in GitHub Desktop.
Save sldenazis/ba0a2b4ee6e8e413e052f1818c823c57 to your computer and use it in GitHub Desktop.
Basic kubectl config get|use-context wrapper
function ktx() {
# Current context
local current_context=$(kubectl config current-context)
if [[ "${1}" == "get" ]] || [[ "${1}" == "set" ]]; then
# Get kube contexts list
declare -a contexts=($(kubectl config get-contexts -o name))
# Map contexts to an associative array
declare -A context_map
for context in "${contexts[@]}"; do
context_map[$context]=1
done
# Print contexts with index and highlight current context
for i in "${!contexts[@]}"; do
if [[ "${contexts[$i]}" == "$current_context" ]]; then
echo -e "\033[1;32m$i: ${contexts[$i]}\033[0m"
else
echo "$i: ${contexts[$i]}"
fi
done
if [[ "${1}" == "set" ]]; then
# Prompt user to select a context
read -p "Select context: " context_index
# Check if the selected context index is valid
if [[ -n "${context_map[${contexts[$context_index]}]}" ]]; then
kubectl config use-context "${contexts[$context_index]}"
else
echo "Invalid context index"
fi
fi
return
else
echo "Usage: $FUNCNAME [get|set]"
return
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment