4

I'm trying to connect to microk8s cluster from remote host using kubectl

kubectl config view

result:

apiVersion: v1
clusters:
- cluster:
    insecure-skip-tls-verify: true
    server: https://ip:16443
  name: microk8s-cluster
contexts:
- context:
    cluster: microk8s-cluster
    user: microk8s-admin
  name: microk8s
current-context: microk8s
kind: Config
preferences: {}
users:
- name: microk8s-admin
  user:
    password: password
    username: username

Credentials like ip, username, password I got using following command on server:

sudo microk8s.config

result:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: *certificate-data*
    server: https://**ip**:16443
  name: microk8s-cluster
contexts:
- context:
    cluster: microk8s-cluster
    user: **user**
  name: microk8s
current-context: microk8s
kind: Config
preferences: {}
users:
- name: admin
  user:
    token: **password**

But if I use

kubectl get node

I got an error: error: You must be logged in to the server (Unauthorized)

mirekphd
  • 4,799
  • 3
  • 38
  • 59
Alexander Karp
  • 328
  • 1
  • 5
  • 20
  • Can you add verbosity `-v=9` into `/var/snap/microk8s/current/args/kube-apiserver` and restart `mikrok8s` for more logs and information? – Vit Sep 08 '20 at 08:53

2 Answers2

8

Instead of using username/password for kubectl user I should use just a token from microk8s.config

Alexander Karp
  • 328
  • 1
  • 5
  • 20
1

In case you wanted a more universal (but sometimes redundant) step-by-step version of the accepted answer (duly upvoted):

  1. (re)generate k8s config file (which OP already did):
$ mkdir -p ~/.kube
$ [sudo] microk8s config > ~/.kube/config
  1. get the k8s API token from the config file (caution: better preserve it more permanently elsewhere, as in kube config it won't survive next logout):
$ KUBE_TOKEN=$(cat ~/.kube/config | grep token | awk -F":" '{print $2}' | xargs) 
# plus:
$ echo $KUBE_TOKEN > ~/.kube/kube-token # recommended
  1. login to the remote k8s API server:
$ kubectl get nodes --token=$KUBE_TOKEN
# or:
$ kubectl get nodes --token=$(cat ~/.kube/kube-token) # recommended

If all of the above fails, you may also try to explicitly login using oc Client Tools (a kubectl drop-in replacement from OKD), which does have the login verb (and is more robust to local config file obfuscation/corruption, as it will re-create the file for you locally, assuming you had the token saved elsewhere):

$ oc login --token=$(cat ~/.kube/kube-token) --server=localhost:16443
mirekphd
  • 4,799
  • 3
  • 38
  • 59