Created
January 31, 2025 12:52
-
-
Save sldenazis/ba0a2b4ee6e8e413e052f1818c823c57 to your computer and use it in GitHub Desktop.
Basic kubectl config get|use-context wrapper
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
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