Skip to content

Instantly share code, notes, and snippets.

@naingyeminn
Created June 11, 2022 17:13
Show Gist options
  • Save naingyeminn/c5b909d38b7fbf7b2d28a5a6079ad8a9 to your computer and use it in GitHub Desktop.
Save naingyeminn/c5b909d38b7fbf7b2d28a5a6079ad8a9 to your computer and use it in GitHub Desktop.
Manage and maintain multiple kubectl versions
#!/bin/bash
BIN_PATH="$HOME/.local/bin"
help_msg () {
echo "Usage: setkube -v [kubectl_version_number | stable]"
echo " setkube -d [kubectl_version_number]"
echo ""
echo " kubectl_version_number = 1.23.5, 1.22.2, etc."
echo ""
echo " -v: set kubectl version"
echo " -d: delete kubectl version"
}
set_kubectl () {
REQ_VER="v$1"
[ ! -d "$BIN_PATH" ] && mkdir -p "$BIN_PATH"
if [ "$REQ_VER" = "vstable" ]; then
KUBE_VER=$(curl -L -s https://dl.k8s.io/release/stable.txt)
else
KUBE_VER=$REQ_VER
fi
KUBECTL="$BIN_PATH/kubectl-$KUBE_VER"
if [ ! -f "$KUBECTL" ]; then
echo "Downloading kubectl $KUBE_VER ..."
curl -Ls "https://dl.k8s.io/release/$KUBE_VER/bin/linux/amd64/kubectl" -o "$KUBECTL"
CHKSUM=$(curl -Ls "https://dl.k8s.io/$KUBE_VER/bin/linux/amd64/kubectl.sha256")
echo "$CHKSUM $KUBECTL" | sha256sum --check &> /dev/null
if [ "$?" != "0" ]; then
echo "The specified version does not exist."
rm $KUBECTL
fi
fi
echo "kubectl $KUBE_VER is ready!"
ln -f -s $KUBECTL $BIN_PATH/kubectl
chmod +x $KUBECTL
}
del_kubectl () {
DEL_VER="$BIN_PATH/kubectl-v$1"
if [ -f "$DEL_VER" ]; then
echo "Deleting kubectl-v$1 ..."
rm -i $DEL_VER
else
echo "The specified version ($1) does not exist."
fi
}
while getopts ":hd:v:" option; do
case $option in
h) # display Help
help_msg
exit;;
d) # delete version
del_kubectl $OPTARG
;;
:)
echo "Error: -${OPTARG} requires an argument."
;;
v)
set_kubectl $OPTARG
;;
\?) # Invalid option
echo "Error: Invalid option"
exit;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment