Managing multiple clusters with kubectl

Installing kubectl is being done to work with a Kubernetes cluster. More often then not, you’ll have to manage multiple clusters, production and staging, multiple production of multiple staging, or your local minikube with other, cloud based clusters.

The kube config file

Usually under the ~/.kube you’ll find the config file. This file is a standard yml file, which for some reason, is not recognized as one. To add a new cluster, you can just edit this file, if you know the sections:

  1. Clusters
    clusters are exactly what you think they are. They have an entry point that must be accessible, a name, and a certificate authority, either pointing to a file (certificate-authority), or the actual certificate data (certificate-authority-data). This section doesn’t include users, in case you want to use more than one user. Well, how do one goes about that? The answer is contexts.
  2. Contexts
    A Context is the combination of both a user (later in this post) and a cluster, so you can have multiple users for the same cluster or the other way around. When you want to connect to another cluster, you are switching contexts, with the idea that you can just switch a user if needed,
  3. Users
    Similar to a cluster, a user contains a certificate location or data and a name. on top of that, it also contains key file location or data.

Adding cluster information

Adding an actual cluster will, in most cases, require you to add information to all sections. You’ll need a new user, a new context and a new cluster. Adding a user to an existing cluster however, will only require adding the user and the context.

Switching contexts

To switch a context, you use the config and use-context command like so:

kubectl config use-context kubernetes-admin@kubernetes
Code language: Bash (bash)
  • kubectl – Kubernetes config tool
  • config – the configuration command
  • use-context – the actual switching order
  • kubernetes-admin@kubernetes – the context name. Yes, it can be an email like text. production will also work.

You can have multiple config files

This post so far dealt with a single file configuration, and the default file at that. You can use multiple files, with the same command(s) with the additional switch

--kubeconfig=<your config file path>
Code language: Bash (bash)

More commands

  • set-context – this will actually create a new context if not already exists. Can be confusing, and generally, I much rather edit my configuration file in my favorite editor and not through the terminal.
  • view – very useful, you can see the configuration without the danger of changing it. Similar to cat, but it will also redact any key or certificate data. you can also use it with the –minify tag, that will only show the active context.

Leave a Reply

Your email address will not be published. Required fields are marked *