Using microk8s with system kubectl

I was already using kubectl with some plugins, and the nice completion already set up, to access remote Kubernetes clusters from my Ubuntu desktop. So when I decided to try microk8s, I wanted to keep the same convenience, without maintaining two configs, or having two different commands. It took a little bit of research to figure out how to make it work, so here it is.

First, find the admin password for your microk8s:

microk8s.kubectl config view | grep password

Now you can create a new context in kubectl, adding in your password on line 2:

kubectl config set-cluster microk8s --server= --certificate-authority=/var/snap/microk8s/current/certs/ca.crt

kubectl config set-credentials microk8s-admin --username=admin --password={password from before}

kubectl config set-context microk8s --cluster=microk8s --namespace=default --user=microk8s-admin

Now you can switch to the new context with kubectl config use-context microk8s and work as before. kubectl config get-contexts will list the other available contexts so you can switch back.