Access Remote Kubernetes Cluster Using Kubectl

Access remote kubernetes cluster using kubectl

Vikash Kumar

2 minute read

If you are working on kubernetes, there is a high chance that you would have needeed to interact with kubernetes cluster very frequently. Most of the time, its remote or lab servers. Instead of login remote machine and accesing cluster , you can use kubectl on your local workstation to interact with remote cluster. Ofcourse you can use official go-client or python-client to access cluster programatically. But if you intend to use kubectl, follow below enumerated steps.

Install Kubectl on your local workstation

Follow this official kubernetes link to install kubectl on your workstation.

Copy ~/.kube/config file from Master node of Kubernetes cluster to your workstation

One of the core file of k8s cluster is ~/.kube/config . This file contains lot of information one of which is, it contains the info which is used to identify the client to Kubernetes API Server.

scp user@IP:.kube/config .

Use this config file to interact with cluster

Use ’–kubeconfig’ option to specify config file in kubectl command

for eg.

kubectl get pods –kubeconfig=config

You can also use environment variable KUBECONFIG like this:

KUBECONFIG=config kubectl get pods

Merge the config in a single config file

If you want to keep a single config view. Follow theses steps:

# Backup your existing kube config file

cp ~/.kube/config config_bk

# Merge the existing config file with cluster’s config

KUBECONFIG=~/.kube/config:config kubectl config view –merge –flatten > out.txt

# Copy the merged ‘out.txt’ as config in ‘~/.kube’

cp out.txt ~/.kube/config

# List all the contexts

kubectl config get-contexts

# Set your cluster context

kubectl config set-context <your context>

Delete the context once finished

kubectl config delete-context <your context>

Kubectl preference of config files

  1. –kubeconfig=config
  2. KUBECONFIG=config
  3. ~/.kube/config

Further readings

Read this nice writeup on kubectl. An overview of kubectl can be found here.

comments powered by Disqus