I can’t be the only one that has this issue and yet I’ve not been able to find any existing solutions.
At work I have to deal with multiple flavours and versions of Kubernetes. Until
very recently stretching all the way from 1.12 up to 1.20. I found it a pain
in the arse trying to ensure I was using the correct kubectl
version; And
helm
, but that’s another story and fortunately less of an issue now.
kubectl
does seem to be very compatible across differing versions, but I was
still keeping different named binaries that looked like this:
ls bin/
[...]
kubectlv1-12
kubectlv1-16
kubectlv1-17
kubectlv1-19
kubectlv1-20
I decided to write a very simple shell function to switch to the correct version:
function kubeset {
if ! which kubectl | grep -q kubectl
then
version=$(curl -L -s https://dl.k8s.io/release/stable.txt)
minor=$(echo $version | sed -E 's/(v[0-9]+)\.([0-9]+)\..*/\1-\2/')
curl -L "https://dl.k8s.io/release/$version/bin/darwin/arm64/kubectl" -o ~/bin/kubectl$minor
chmod +x ~/bin/kubectl$minor
rm -f ~/bin/kubectl && ln -s ~/bin/kubectl$minor ~/bin/kubectl
fi
version=$(kubectl version | grep Server | sed -E 's/.*(v[0-9]+)\.([0-9]+)\.([0-9]+).*/\1\.\2\.\3/')
if [ $version ]
then
minor=$(echo $version | sed -E 's/(v[0-9]+)\.([0-9]+)\..*/\1-\2/')
if test -f ~/bin/kubectl$minor
then
echo "Setting kubectl to $minor"
else
echo "Downloading kubectl $version and setting to that"
curl -L https://dl.k8s.io/release/$version/bin/darwin/arm64/kubectl -o ~/bin/kubectl$minor
chmod +x ~/bin/kubectl$minor
fi
rm ~/bin/kubectl && ln -s ~/bin/kubectl$minor ~/bin/kubectl
fi
}
(I don’t care about patch version compatibility, just minor version)
.
Thankfully we’ve now torn down the 1.12 cluster (because it’s easier to tear down and re-write everything than upgrade K8s; more snark) so I have less versions to deal with.
[EDIT: 2021-03-30] This is actually more useful than I realised. Sometimes kubectx
doesn’t work so well with mismatched kubectl
versions. But this kubeset
thing does the trick. Nice.
[EDIT: 2025-01-30] Had reason to re-visit this. Updated to handle no initial install of kubectl, Apple Silicon, latest download links, and to make it a bit more clever.