Last active
August 3, 2021 18:11
-
-
Save studiotomi/68015b9d52f70ad5b8fe5aedcd002143 to your computer and use it in GitHub Desktop.
Set kubernets current-context from one of the contexts in the config file
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
kccontexts() { | |
# Works with kubectl v1.4.0 and the config file generated by gcloud containers clusters get-credentials | |
# If you pass in an arg, then we will filter the contexts for that string | |
# The following block creates a list of the contexts and filters if an argument | |
# is passed in. | |
if [[ $1 ]] | |
then | |
options=(`kubectl config get-contexts -o name | sort | grep $1`) | |
else | |
options=(`kubectl config get-contexts -o name | sort`) | |
fi | |
if [[ ${#options[@]} == 0 ]] | |
then | |
msg="No contexts found" | |
if [[ $1 ]] | |
then | |
msg="$msg - check the string you are filtering with" | |
else | |
msg="$msg - either there are no contexts, or the config file is a different format than expected" | |
fi | |
echo $msg | |
return 0 | |
fi | |
current_context=`kubectl config current-context` | |
echo "Currently using $current_context" | |
echo "----------" | |
# Walk through the contexts, and display them with a numeric choice | |
for i in ${!options[@]}; do | |
printf "%3d%s) %s\n" $((i+1)) "${choices[i]:- }" "${options[i]}" | |
done | |
# Prompt for the number of the context to swith to | |
prompt="Pick a Context(1-${#options[@]}):" | |
read -rp "$prompt" num; | |
# Confirm a valid input (numbers only, 0 < num < number of contexts) | |
if [[ "$num" = '' ]] || [[ "$num" = *[![:digit:]]* ]] || (( $num <= 0 || $num > ${#options[@]} )) | |
then | |
echo "Invalid option: current context not changed"; | |
return 1 | |
else | |
((num--)); | |
msg="${options[num]}" | |
echo "You are now using $msg" | |
kubectl config use-context $msg; | |
return 0 | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment