English
Note

In this Kubernetes guide, we will dive deep into Kubeconfig - what is it, its file structure, and how to merge/update/delete it with practical examples.

How to Create & Use Kubeconfig File in Kubernetes cover image

Kubernetes is the go-to container orchestration platform for managing containerized applications at scale.

A fundamental aspect of interacting with Kubernetes clusters is the utilization of Kubeconfig files.

In this blog, let's dive into the specifications of Kubeconfig files, their structure, purpose, and how they play a pivotal role in enabling secure communication with Kubernetes clusters.

What is a Kubeconfig file?

A Kubeconfig file is a configuration file that is used to define and manage access to Kubernetes clusters. It sum ups crucial information required for authentication, and context switching between clusters, and specifies the default behavior for kubectl commands.

It is a YAML file with all the Kubernetes Cluster details, certificates, and secret tokens to authenticate the cluster.

You might get this config file directly from the cluster administrator or from a cloud platform if you are using a managed Kubernetes cluster.

When you use kubectl, it uses the information in the kubeconfig file to connect to the Kubernetes cluster API.

The default location of the Kubeconfig file is $HOME/.kube/config

You can view the Kubeconfig file by going to your home directory, then searching for the .kube directory, and then the file config.

These are the commands that you can use, and replace with your customized home information.

cd /home/kanika/.kube
cat config

This image of the Kubeconfig file can be very confusing to understand and hence, the following section gives a brief description of the internal structure of a Kubeconfig file.

Kubeconfig File Structure

A Kubeconfig file is typically organized into these several sections:

  • Clusters: This section defines the Kubernetes clusters with which you want to interact. It includes the cluster's server URL, and optionally, the certificate authority data for secure communication.

  • Contexts: Contexts define the combination of a cluster and a user, along with the namespace to operate within. They allow you to easily switch between different clusters and user identities.

  • Users: The Users section contains information about the entities (such as developers or service accounts) that are allowed to access the cluster. This can include client certificates, private keys, and authentication tokens.

Here is a sample Kubeconfig file which you can inspect:

apiVersion: v1
kind: Config
clusters:
- name: my-cluster
  cluster:
    server: https://my-cluster.example.com
    certificate-authority-data: <base64-encoded-ca-data>
contexts:
- name: my-context
  context:
    cluster: my-cluster
    user: my-user
    namespace: default
current-context: my-context
users:
- name: my-user
  user:
    client-certificate-data: <base64-encoded-client-cert>
    client-key-data: <base64-encoded-client-key>

After getting a hold of what a Kubeconfig file is and understanding its structure, it's time to unwrap its various use cases in the following section.

What is the Use of Kubeconfig File?

Kubeconfig files can have a lot of use cases in Kubernetes. Here are a few of them.

1. Authentication

One of the major functions of the Kubeconfig file is to provide authentication credentials for users and service accounts to access Kubernetes clusters.

These credentials can include client certificates, private keys, and authentication tokens.

By specifying the correct credentials in the Kubeconfig file, users and applications can securely authenticate themselves with the cluster.

Here's an example.

If you're using client certificates for authentication, your Kubeconfig file might look like this:

users:
- name: my-user
  user:
    client-certificate-data: <base64-encoded-client-cert>
    client-key-data: <base64-encoded-client-key>

2. Switching between Clusters and Contexts

The Kubeconfig file allows you to seamlessly switch between different Kubernetes clusters and contexts.

This is particularly useful when you're working with multiple clusters, each serving a different purpose.

Let's say you have a development cluster and a production cluster. You can define two contexts in your Kubeconfig file, each associated with a different cluster and user.

Here, you can use the kubectl config use-context command to switch between these contexts.

kubectl config use-context development-cluster
kubectl get pods

3. Setting Default Namespace

The Kubeconfig file can specify a default Kubernetes namespace for commands that don't explicitly provide one. This saves you from having to specify the namespace every time you run a command.

Let's look at an example.

If you frequently work within the my-namespace namespace, you can set it as the default in your context.

contexts:
- name: my-context
  context:
    cluster: my-cluster
    user: my-user
    namespace: my-namespace  # Default namespace

4. Managing Multiple Environments

Kubeconfig files are invaluable for managing different environments, such as development, testing, and production. Each environment can have its own cluster, user, and context configurations.

Let's look at an example.

You might have three different contexts in your Kubeconfig file: dev-context, test-context, and prod-context.

Each context points to a separate cluster, allowing you to interact with the corresponding environment.

Overall, the Kubeconfig file simplifies your interaction with Kubernetes clusters by providing a centralized way to manage authentication, context switching, and other cluster-specific configurations.

Its flexibility makes it an essential tool for both developers and administrators working with Kubernetes.

How to Create a Kubeconfig file?

Creating a Kubeconfig file involves accumulating all the necessary configuration details for clusters, users, and contexts.

There can be two ways of creating a Kubeconfig file:

  1. Manually, and
  2. Using the kubectl commands.

1. Manual Process

Below, I'll walk you through the process step by step, along with an example:

Step 1: Collect Cluster Information

Gather the details of the Kubernetes cluster you want to configure in the Kubeconfig file, which will include:

  • Cluster name

  • Server URL (API server endpoint)

  • Certificate authority data (if applicable)

Step 2: Collect User Information

Determine the authentication method you'll use for accessing the cluster and gather the corresponding user information:

For client certificate authentication:

  • Client certificate data (Base64-encoded)

  • Client key data (Base64-encoded)

For token-based authentication:

  • Authentication token

Step 3: Define Contexts

A context is a combination of a cluster and a user, along with an optional namespace. Define the context(s) for the cluster(s) and user(s) you want to work with.

Here's an example of a simple Kubeconfig file:

apiVersion: v1
kind: Config
clusters:
- name: my-cluster
  cluster:
    server: https://my-cluster.example.com
    certificate-authority-data: <base64-encoded-ca-data>
contexts:
- name: my-context
  context:
    cluster: my-cluster
    user: my-user
    namespace: default
current-context: my-context
users:
- name: my-user
  user:
    client-certificate-data: <base64-encoded-client-cert>
    client-key-data: <base64-encoded-client-key>
  • my-cluster represents the cluster name, and the cluster details include the server URL and certificate authority data.
  • my-user represents the user name, and the client certificate and key data are provided for authentication.
  • my-context combines the my-cluster cluster and my-user user. It also specifies the default namespace as default.
  • current-context indicates that the my-context should be considered the current context.

Remember that in a real-world scenario, the placeholder values like <base64-encoded-ca-data>, <base64-encoded-client-cert>, and <base64-encoded-client-key> should be replaced with the actual certificate and key data encoded in Base64 format.

2. Using the Kubectl commands

You can also use tools like kubectl to generate Kubeconfig files.

For example, to generate a Kubeconfig file for a specific cluster and user, you can use the following commands. By using these you can not only create new Kubeconfig files but, can also update them with respective values.

Command 1:

kubectl config set-cluster my-cluster --server=https://my-cluster.example.com --certificate-authority=<path-to-ca-file>

Command 2:

kubectl config set-credentials my-user --client-certificate=<path-to-client-cert-file> --client-key=<path-to-client-key-file>

Command 3:

kubectl config set-context my-context --cluster=my-cluster --user=my-user --namespace=default
kubectl config use-context my-context

These commands will automatically update your ~/.kube/config file with the specified configuration.

Let's see the explanations of some of the questions related to multiple Kubeconfig files.

How to Merge Kubeconfig Files?

Merging kubeconfig files allows you to combine configurations for multiple Kubernetes clusters, contexts, and authentication details into a single file.

This is particularly useful when managing connections to multiple clusters or sharing configurations across different environments.

Here's how you can merge kubeconfig files.

1. Using the kubectl Command

Kubernetes provides a built-in command to merge kubeconfig files.

For this open a terminal and use the following syntax:

kubectl config view --merge --flatten > merged-kubeconfig

This command merges all kubeconfig files that are found in the default locations (~/.kube/config and files specified by the KUBECONFIG environment variable), flattens the resulting configuration, and saves it to a file named merged-kubeconfig.

2. Manually Merging Kubeconfig Files

If you want more control over the merging process, you can manually edit and combine kubeconfig files. Here's how you can do it:

Open the source kubeconfig file (let's call it source-kubeconfig) and copy its contents.

Open the target kubeconfig file (e.g., ~/.kube/config) in a text editor.

Find the clusters, users, contexts, and current-context sections in the target kubeconfig file.

Paste the corresponding sections from the source kubeconfig into the appropriate sections of the target kubeconfig.

For example, you might have something like the code snippet in your target kubeconfig.

apiVersion: v1
kind: Config
clusters:
- name: cluster1
  ...
users:
- name: user1
  ...
contexts:
- name: context1
  ...
current-context: context1

If your source kubeconfig has another cluster, user, and context, you would copy the respective sections and paste them into the target kubeconfig.

Note

Remember that when merging kubeconfig files, you need to handle potential conflicts in cluster, user, and context names.

Make sure each context is unique to avoid confusion. Additionally, always keep backups of your kubeconfig files before making any changes, to avoid data loss.

How to Use Multiple Kubeconfig Files?

Here's how you can use multiple kubeconfig files.

1. Setting the KUBECONFIG Environment Variable

To use multiple kubeconfig files, you can set the KUBECONFIG environment variable to a list of paths to kubeconfig files, separated by colons (on Linux/macOS) or semicolons (on Windows).

Each kubeconfig file in the list will contribute its configuration to the kubectl commands.

For Linux/macOS, use the following command.

export KUBECONFIG=/path/to/first/kubeconfig:/path/to/second/kubeconfig

For Windows (PowerShell), use:

$env:KUBECONFIG="C:\path\to\first\kubeconfig;C:\path\to\second\kubeconfig"

For Windows (Command Prompt), use:

set KUBECONFIG=C:\path\to\first\kubeconfig;C:\path\to\second\kubeconfig

2. Using kubectl Commands

Once you have set the KUBECONFIG environment variable to include multiple kubeconfig files, the kubectl command-line tool will read and use configurations from all the specified files.

For example, if you have contexts defined in both kubeconfig files, you can switch between them using the kubectl config use-context command:

kubectl config use-context context-name

Context Priority

When you use multiple kubeconfig files, context names should be unique across all the files to avoid ambiguity.

If you have contexts with the same name in different files, the context from the kubeconfig file listed earlier in the KUBECONFIG variable takes precedence.

Checking Configuration

You can view the merged configuration from all the kubeconfig files by running:

kubectl config view

Frequently Asked Questions (FAQs)

1. How to find & export a kubeconfig file?

The kubeconfig file is usually located at ~/.kube/config by default. You can export the path using the following command:

export KUBECONFIG=/path/to/your/kubeconfig

2. Where is the kubeconfig file located (Kubeconfig file default location)?

The default location of the Kubeconfig file is $HOME/.kube/config

3. What command is used to create Configmaps from the file?

To create ConfigMaps from a file, you can use the kubectl create configmap command. Here's the basic syntax:

kubectl create configmap <configmap-name> --from-file=<path-to-file-or-directory>

Replace <configmap-name> with the desired name for your ConfigMap and <path-to-file-or-directory> with the path to the file or directory containing the data you want to include in the ConfigMap.

With this, we have reached the end of the blog, and it's time to have a basic summary of what we covered in this guide.

Summary - Kubeconfig File

In conclusion, the Kubeconfig file is a crucial element in Kubernetes, serving as a configuration blueprint for accessing clusters. The examples demonstrated, how it enables secure connections to clusters.

This file empowers users to effortlessly manage multiple clusters, contexts, and authentication methods.

Through comprehensive steps, you explored its creation, modification, and merging, unveiling the potential to seamlessly switch contexts.

Multiple methods of connection and generation have been outlined, representing its flexibility. The power of Kubeconfig lies in its ability to simplify access, making Kubernetes management more accessible and efficient.

Priyansh Khodiyar's profile

Written by Priyansh Khodiyar

Priyansh is the founder of UnYAML and a software engineer with a passion for writing. He has good experience with writing and working around DevOps tools and technologies, APMs, Kubernetes APIs, etc and loves to share his knowledge with others.