How to use "kubectl" command instead of "sudo kubectl"

E235 picture E235 · Jul 11, 2018 · Viewed 17.8k times · Source

For every command with kubectl I need to use sudo kubectl.

I understand the security perspective but I am working on a test environment and I want to be able use it without sudo.

I tried to run sudo -i and use the root account to runkubectl get pods but I received:

The connection to the server localhost:8080 was refused - did you
specify the right host or port?

I noticed that when I was playing with https://labs.play-with-k8s.com, the user is root and I can run kubectl freely.

I wanted to have the same thing on my Ubuntu machine with my Minikube.

When I runkubectl get pods with my regular account I received the error:

error: unable to read client-key /home/myuser/.minikube/client.key for minikube due to open /home/myuser/.minikube/client.key: permission denied

I supposed there are two ways:
1. Give everyone access to /home/myuser/.minikube/
2. Give my account permissions to run kubectl without sudo

EDIT:
Following @Konstantin Vustin request, here are the requested information:

myuser@ubuntu:/usr/local/bin$ ls -l  $(which kubectl)
-rwxrwxr-x 1 myuser myuser 54308597 Jun 13 05:21 /usr/local/bin/kubectl

myuser@ubuntu:/usr/local/bin$ ls -la ~ | grep kube
drwxr-xr-x  5 myuser myuser   4096 Jun 17 02:25 .kube
drwxrwxr-x 10 myuser myuser   4096 Jun 13 05:18 .minikube

myuser@ubuntu:/usr/local/bin$ ls -l ~/.kube
total 24
drwxr-xr-x  3 root  root  4096 Jun 13 05:26 cache
-rw-------  1 myuser myuser 911 Jun 13 05:27 config
drwxrwxr-x  3 myuser myuser 4096 Jul 11 01:37 http-cache

Answer

Webber picture Webber · Jul 11, 2018

Fix file permissions

Most likely your kubectl files are not owned by your user.

You can set these permissions using below command.

sudo chown -R $USER $HOME/.kube

Run kubectl with sudo

Alternatively you can run kubectl as sudo user using a persistent sudo shell.

sudo -s

then run your kubectl commands

kubectl get pods

kubectl describe <resource_type> <resource_name>

finally exit the sudo shell

exit