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 {
	version=$(kubectl version --short | grep Server | sed -E 's/.*(v[0-9]+)\.([0-9]+)\.([0-9]+).*/\1\.\2\.\3/')
	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://storage.googleapis.com/kubernetes-release/release/$version/bin/darwin/amd64/kubectl -o ~/bin/kubectl$minor
		chmod +x ~/bin/kubectl$minor
	fi
	rm ~/bin/kubectl && ln -s ~/bin/kubectl$minor ~/bin/kubectl
}

(I don’t care about patch version compatibility, just minor version)

It does require that there is an initial version of kubectl available. I guess it could be adjusted to handle that case, but if you’re not careful you end up taking something simple and elegant and ending up with this; Although snark aside this would be nice as a hook/extension to kubectx.

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.