How to connect to your remote kuberenetes cluster with kubectl from you local?

You’ve just set up your kubernetes cluster. Excellent, now you want to start deploying your specs…but they are on a repo on your local machine.

All good let’s setup your kubeconfig file so you can connect to your k8s api with kubectl.

  1. Log into your server

  2. Create a service account spec:

kind: ServiceAccount
  name: admin-user
  namespace: kube-system
  1. Create the account

    kubectl create -f server-account.yaml

  2. Create the cluster role binding:

kind: ClusterRoleBinding
  name: admin-user
  kind: ClusterRole
  name: cluster-admin
- kind: ServiceAccount
  name: admin-user
  namespace: kube-system
  1. Apply the role binding

kubectl apply -f admin-role-binding.yml

  1. Find the secrets used by the service account
kubectl describe serviceAccounts admin-user
Name:                devacc
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   devacc-token-47p8n
Tokens:              devacc-token-47p8n
Events:              <none>
  1. Fetch the token

kubectl describe secrets devacc-token-47p8n

Keep the token

  1. Get the certificate info for the cluseter
kubectl config view --flatten --minify > cluster-cert.txt
cat cluster-cert.txt

Copy certificate-authority-data and server from the output.

  1. Now you can create your kubeconfig file

Create a file called my-service-account-config.yaml and substitute the values for token, certificate-authority-data and server

apiVersion: v1
kind: Config
- name: admin-user
    token: <replace this with token info>
- cluster:
    certificate-authority-data: <replace this with certificate-authority-data info>
    server: <replace this with server info>
  name: self-hosted-cluster
- context:
    cluster: self-hosted-cluster
    user: devacc
  name: devacc-context
current-context: devavv-context
  1. Copy the file to $HOME/.kube

  2. Tell kubectl to use that context:

kubectl config –kubeconfig=$HOME/.kube/my-service-account-config.yaml set-context svcs-acct-context

It is better to append it to the base config