The Ops Community ⚙️

Cover image for kubectl context like a pro
Alexandru Dejanu
Alexandru Dejanu

Posted on • Updated on

kubectl context like a pro

If your work involves working with multiple Kubernetes clusters, then this might be for you.

A Kubernetes config file describes clusters, users, and contexts. You can have multiple contexts in order to target different Kubernetes clusters.

A standard config file structure:

apiVersion: v1
kind: Config
preferences: {}

clusters:
- cluster:
  name: <cluster_name>
...

users:
- name: <user_name>
...

contexts:
- context:
  name: <context_name>

Enter fullscreen mode Exit fullscreen mode

You can check your config using:
kubectl get config

Without further ado, let's take the example of merging two config files(one for each cluster) together:

# create backup for current config
cp ~/.kube/config ~/.kube/config.bak

# merge the 2 configs
KUBECONFIG=~/.kube/config:/path/to/new/config kubectl config view --flatten > ~/intermediate_config

# replace the current config with the intermediate_config
mv ~/intermediate_config ~/.kube/config
Enter fullscreen mode Exit fullscreen mode

A context is a combination of a cluster and user credentials, we can switch between contexts using:

  • Check the current context:
    kubectl config current-context

  • Check defined clusters
    kubectl config get-clusters

  • Switch between clusters:
    kubectl config use-context <context_name>

⚠️ A file that is used to configure access to a cluster is usually, called kubeconfig (placed here ~/.kube/config), but you can easily override the location by using --kubeconfig=<path_to_config> flag.

Top comments (2)

Collapse
 
audioboxer217 profile image
Scott Eppler

I like the use of kubectl config view --flatten to merge two kubeconfigs into one!

Collapse
 
derlin profile image
Lucy Linder

Once my kubeconfigs are merged, I personally use kubectx and kubens to easily switch context and namespaces. Saves me lots of time and trouble!
github.com/ahmetb/kubectx