Managing multiple Kubernetes clusters with kubectl

kubernetes Jan 18, 2023

Learn how to use kubectl CLI to manage multiple Kubernetes clusters. Import new config, add cluster, user, and context. Switch between contexts to manage different clusters.

Kubernetes is an open-source platform for managing containerized workloads and services, allowing you to easily deploy and run applications in a cloud-native environment. The kubectl command-line interface (CLI) is a key component of Kubernetes, providing a powerful and flexible way to manage clusters and deploy applications.

One useful feature of kubectl is the ability to manage multiple clusters using a single CLI. In this post, I'll show you how to import a new Kubernetes config file and use the kubectl CLI to manage multiple clusters.


Make a backup

Assume that something can go wrong, and you will lose all your configuration data.

So, be cautious and backup your default configuration file:

cp ~/.kube/config /path/to/BACKUP_FILE

Import an existent config file

To import an existing Kubernetes config file using kubectl, you can use the kubectl config command.

Here's an example of how you can do it:

First, copy the config file to your local machine and ensure it is in the right location (e.g., ~/.kube/config).

Run the following command to view the current contexts in your config:

kubectl config get-contexts

This will list the contexts that are currently defined in your config.

  1. Run the following command to import the new config file:
IMPORTANT: You must have a different context name or your configuration will be replaced!
# NOTE: you may experience a situation where you can't define the
#       `/path/to/FILE1` and `/path/to/COMBINED_FILE` as the same file if
#       you ran it in the same command.
# 
#       Check this post comments to see more about this discussion.
#
# The example below should work on any condition

export KUBECONFIG=/path/to/FILE1:/path/to/FILE2
kubectl config view --flatten > /path/to/COMBINED_FILE

# Replace the main config file
cp /path/to/COMBINED_FILE ~/.kube/config

Replace NEW_CONFIG_FILE with the path to your new config file.

This will merge the new config file with your existing config, adding any new contexts, users, or clusters that are defined in the file.

You can then use the kubectl config use-context command to switch between the different contexts and manage the different clusters.

For example:

kubectl config use-context NEW_CONTEXT_NAME

This will set the NEW_CONTEXT_NAME context as the current context, and you can use kubectl to manage the cluster associated with that context.

References

Tags

Luiz Costa

I am a software engineer at Red Hat / Ansible. I love automation tools, games, and coffee. I am also an active contributor to open-source projects on GitHub.