DEV Community

Cover image for kubectl context like a pro

kubectl context like a pro

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

☸️ A file that is used to configure access to a cluster is called kubeconfig(usually placed at ~/.kube/config), but you can easily override the location by using --kubeconfig=<path_to_config> flag or using KUBECONFIG environment variable export KUBECONFIG=<path/to/your_kubeconfig>. A Kubernetes config file describes clusters, users, and contexts. You can use multiple contexts to target different Kubernetes clusters.

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 render your current config: kubectl config view.

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

# 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.You can:

  • List contexts: kubectl config get-contexts

  • Check the current context: kubectl config current-context

  • Switch to desired context: kubectl config use-context <context_name>

  • Delete context: kubectl config delete-context <context_name>

⚠️ Running aws eks update-kubeconfig --region <us-east-1> --name <cluster_name> pulls your cluster's API endpoint and CA data to create/update a context in your local kubeconfig. This automatically sets that cluster as your active target, so any immediate kubectl commands will execute against it.

$ aws eks update-kubeconfig --region us-east-1 --name demo-eks
...
$ kubectl config current-context
arn:aws:eks:us-east-1:255656399702:cluster/demo-eks
Enter fullscreen mode Exit fullscreen mode

Top comments (0)