How to configure access to Kubernetes cluster

Photo by Loik Marras on Unsplash

How to configure access to Kubernetes cluster

Overview:

This post shows three different ways of how to configure access to your Kubernetes cluster by using kubeconfig file.

kubeconfig files are used to organize information about clusters, users, namespaces, and authentication mechanisms.

Note: A file that is used to configure access to clusters is called a kubeconfig file. This is a generic way of referring to configuration files. It does not mean that there is a file named kubeconfig.

Make sure that you have ~/.kube directory. If not, create it

Kubeconfig file structure:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: <ca-data-here>
    server: https://your-k8s-cluster.com
  name: <cluster-name>
contexts:
- context:
    cluster:  <cluster-name>
    user:  <cluster-name-user>
  name:  <cluster-name>
current-context:  <cluster-name>
kind: Config
preferences: {}
users:
- name:  <cluster-name-user>
  user:
    token: <secret-token-here>

Main components of the file are:

  • certificate-authority-data: Cluster CA
  • server: Cluster endpoint (IP/DNS of the master node)
  • name: Cluster name
  • user: name of the user/service account
  • token: Secret token of the user/service account

Preference of using kubeconfig file:

The following preference is used in determining from where to use the configuration info for the cluster:

  1. Usage of --kubeconfig flag
  2. Usage of KUBECONFIG environment variable
  3. Usage of the default config file at $HOME/.kube/config

Configure access to the cluster via kubectl context

A kubernetes context is just a set of access parameters that contains a Kubernetes cluster, a user, and a namespace. Kubernetes context is essentially the configuration that you use to access a particular cluster & namespace with a user account.

  1. Move your kubeconfig file to the ~/.kube
  2. Check your existing contexts with:
    kubectl config get-contexts
    
  3. Set your current context with
    kubectl config use-context [cluster_name]
    
  4. Test the connection with:
    kubectl get nodes
    

Configure access via KUBECONFIG env variable:

Set the variable by using the following command:

export KUBECONFIG=$HOME/.kube/[kubeconfig_file]

Configure access via --kubeconfig option:

Example:

kubectl get nodes --kubeconfig=$HOME/.kube/[kubeconfig_file]

Reference:

  1. How to install Kubectl on Amazon Linux 2
  2. Kubeconfig File Explained With Practical Examples
  3. Organizing Cluster Access Using kubeconfig Files
  4. Configure Access to Multiple Clusters
  5. How to configure kubectl with cluster information from a .conf file?
  6. What is kubernetes context and kubernetes context Tutorial