Skip to content

Instantly share code, notes, and snippets.

@caruccio
Created September 3, 2024 21:16
Show Gist options
  • Save caruccio/7a5c3358d70dcbcc5e2409808b21c0d1 to your computer and use it in GitHub Desktop.
Save caruccio/7a5c3358d70dcbcc5e2409808b21c0d1 to your computer and use it in GitHub Desktop.
Select kubectl binary by version
#!/bin/bash
function download()
{
KUBECTL_VERSIONS=(
$(curl -s "https://api.github.com/repos/kubernetes/kubernetes/releases?per_page=100" \
| jq -r '.[] | .tag_name' \
| grep '^v[0-9]\.[0-9][0-9]\?\.[0-9][0-9]\?$' \
| sort -Vr \
| awk -F . '!a[$1 FS $2]++' \
| sort -V)
)
echo Found ${#KUBECTL_VERSIONS[*]} kubectl versions: ${KUBECTL_VERSIONS[*]}
for version in ${KUBECTL_VERSIONS[@]}; do
bin=kubectl_${version}
if [ -e "$bin" ]; then
echo Already exists: $bin
else
echo Downloading $bin
curl -skL https://storage.googleapis.com/kubernetes-release/release/${version}/bin/linux/amd64/kubectl > $bin
fi
done
}
function usage()
{
echo 'Usage: kubectl use-version [--download]'
echo
echo 'This command creates a symlink `kubectl` -> `kubectl_v[VERSION]` for the selected version available in your system.'
echo
echo 'You can download latest kubectl versions using the flag `--download`:'
echo
echo '$ mkdir ~/bin'
echo '$ cd ~/bin'
echo '$ kubectl use-version --download'
echo '$ export PATH="$PATH:~/bin"'
echo '$ kubectl use-version'
exit ${1:-0}
}
while [ $# -gt 0 ]; do
case $1 in
-h|--help) usage ;;
-d|--download) download; exit
esac
done
if ! KUBECTL_BIN=$(which kubectl 2>/dev/null); then
echo kubectl not found in PATH
exit 1
fi
if ! [ -L "$KUBECTL_BIN" ]; then
echo kubectl is not a symlink
exit 1
fi
KUBECTL_DIR=${KUBECTL_BIN%/*}
shopt -s nullglob
KUBECTL_VERSIONS=(
${KUBECTL_DIR}/kubectl_v*
)
shopt -u nullglob
if [ ${#KUBECTL_VERSIONS[*]} -eq 0 ]; then
echo "No kubectl binaries found in $KUBECTL_DIR: expected filename format is 'kubectl_v[VERSION]'"
exit 1
fi
KUBECTL_TARGET=$(printf "%s\n" ${KUBECTL_VERSIONS[*]} | sort -n -r | fzf -1 --ansi --no-preview --cycle)
if [ -f "$KUBECTL_TARGET" ]; then
ln -vfs "$KUBECTL_TARGET" "$KUBECTL_BIN"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment