k3s permission denied when using kubectl

When you install k3s as described on k3s.io, you can run into the following error when you try a kubectl get po without sudo:

Unable to read /etc/rancher/k3s/k3s.yaml, please start server with -write-kubeconfig-mode to modify kube config permissions.
error: error loading config file “/etc/rancher/k3s/k3s.yaml”: open /etc/rancher/k3s/k3s.yaml: permission denied

There are a couple of solutions to run kubectl without sudo on k3s, without the need to reinstall k3s. I will list 2 of them

Option one:

Add the following line to /etc/systemd/system/k3s.service.env

echo K3S_KUBECNFIG_MODE=\"644\" >> /etc/systemd/system/k3s.service.env

Above command adds this line and after a reboot you can use kubectl without any issues.

Option two:

Copy the context to your ~/.kube/config and set this config as the default.

sudo cp /etc/rancher/k3s/k3s.yaml ~/.kube/config && chown $USER ~/.kube/config && chmod 600 ~/.kube/config && export KUBECONFIG=~/.kube/config

You probably want to store that export to your bashrc or bash_profile. After you changed this you can use kubectl in a new terminal.

Option three (bonus):

For some quick ad-hoc commands use this, next reboot you need to run this command again.

sudo chmod 644 /etc/rancher/k3s/k3s.yaml

Should you be doing this?

If you use the k3s setup for anything professional, such as an IOT solution, edge or anything else in an environment where you do not want unwanted access to this machine: keep using the sudo command. With above steps you are removing a layer of security from your setup.

If you use the k3s environment for a quick test lab to prepare for certification, tests, playground etc. Then it is probably fine to use above commands. But please stay aware of the role and the use-case of the machine. If it leaves your supervision, wipe it and set it up again.

Read more here: Source link