Kubernetes context is not set

11/20/2018

I have this config file

apiVersion: v1
clusters:
- cluster:
    server: [REDACTED] // IP of my cluster
  name: staging
contexts:
- context:
    cluster: staging
    user: ""
  name: staging-api
current-context: staging-api
kind: Config
preferences: {}
users: []

I run this command

kubectl config --kubeconfig=kube-config use-context staging-api

I get this message

Switched to context "staging-api".

I then run

kubectl get pods

and I get this message

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

As far as I can tell from the docs

https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/

I'm doing it right. Am I missing something?

-- praks5432
kubernetes

2 Answers

11/17/2019

You need to fetch the credentials of the running cluster. Try this:

gcloud container clusters get-credentials <cluster_name> --zone <zone_name>

More info:

https://cloud.google.com/sdk/gcloud/reference/container/clusters/get-credentials

-- ttfreeman
Source: StackOverflow

11/20/2018

Yes, Try the following steps to access the kubernetes cluster. This steps assumes that you have your k8s certificates in /etc/kubernetes.

You need to setup the cluster name, Kubeconfig, User and Kube cert file in following variables and then simply run those commands:

CLUSTER_NAME="kubernetes"
KCONFIG=admin.conf
KUSER="kubernetes-admin"
KCERT=admin

cd /etc/kubernetes/

$ kubectl config set-cluster ${CLUSTER_NAME} \
  --certificate-authority=pki/ca.crt \
  --embed-certs=true \
  --server=https://${KUBERNETES_PUBLIC_ADDRESS}:6443 \
  --kubeconfig=${KCONFIG}

$ kubectl config set-credentials kubernetes-admin \
  --client-certificate=admin.crt \
  --client-key=admin.key \
  --embed-certs=true \
  --kubeconfig=/etc/kubernetes/admin.conf

$ kubectl config set-context ${KUSER}@${CLUSTER_NAME} \
  --cluster=${CLUSTER_NAME} \
  --user=${KUSER} \
  --kubeconfig=${KCONFIG}

$ kubectl config use-context ${KUSER}@${CLUSTER_NAME} --kubeconfig=${KCONFIG}
$ kubectl config view --kubeconfig=${KCONFIG}

After this you will be able to access the cluster. Hope this helps.

-- Prafull Ladha
Source: StackOverflow