Kubernetes 101 : The KubeConfig file - Users, Contexts, Namespaces, ... -
The "kubeconfig" file contains all the parameters and credentials we need to connect, and to identify with the API-server, which is the entry point to the kubernetes cluster.
The "kubeconfig" file contains information related to the IP address of the API-server, the client's certificates, ..., as we can see below:
Having that file, we don't need to mention all the above parameters when we connect to the API-server through the "kubectl" command for example.
We could just mention the file as below:
The config file is located in the home directory "~/.kube/config".
The "kubectl" utility looks for the config file in the above default directory, so we don't have to mention the name of the file either, we simply use the below command:
The "kubeconfig" file components:
cluster: defines all the clusters we need to access - development, production, testing, ... -
Users: represents the users accounts that we use to access the kubernetes clusters - Admin, tester, ... -.
It also contains all the certificates needed for a user to authenticate with the cluster.
The context information is also mentioned, it indicates which context we will use to access which cluster - user@cluster -, for example:
We don't need to use "kubectl apply" to create the config file from its Yaml configuration.
The "default" context is mentioned in the Yaml file of the "kubeconfig" as the "current-context" parameter.
We could display the "kubeconfig" file using the below command:
When using a non-default location for the config file, we would need to mention its location:
We change contexts using the below command:
The changes are reflected in the config file "current-context" parameter.
Switching namespaces using contexts:
Using the "contexts.context.namespace" field in the config file, we attach a context to a namespace, switching to a context puts us automatically in its namespace.
The format of the certificates:
We could use the parameter "clusters.cluster.certificate-authority-data" to put the actual certificate instead of its location - "/etc/kubernetes/pki/ca.crt" - defined as the "clusters.cluster.certificate-authority" parameter .
We would need to encode it first as shown below, before pasting it in the field "clusters.cluster.certificate-authority-data" using the below command :
We then paste the output in the config file.
To decode a certificate to put it in a file, we use the below command: