4/445 min
Foundation
kubectl & kubeconfig
Master the CLI and configuration file that connect you to any Kubernetes cluster.
beginner45 minRead β Lab β Quiz β Practice
π§ Brain Warm-Up
π§ Brain Warm-Up: If you manage 5 clusters (dev, staging, prod-us, prod-eu, local-minikube), how does a single kubectl binary know which cluster to talk to? Where are credentials stored, and how do you switch between them without breaking a live deployment?
kubeconfig: Your Cluster Address Book
kubectl is a stateless binary β it reads a kubeconfig file on every invocation to know where to connect and how to authenticate. By default this file lives at ~/.kube/config.
A kubeconfig file has three sections and one pointer:
apiVersion: v1
kind: Config
clusters: # 1. Cluster endpoints (API server URL + CA cert)
- name: prod-cluster
cluster:
server: https://api.prod.example.com:6443
certificate-authority-data: <base64-CA>
users: # 2. Credentials (client cert, token, or auth provider)
- name: prod-admin
user:
client-certificate-data: <base64-cert>
client-key-data: <base64-key>
contexts: # 3. Named bindings: cluster + user + namespace
- name: prod-context
context:
cluster: prod-cluster
user: prod-admin
namespace: production
current-context: prod-context # β active contextContexts: Named Cluster Sessions
A context is a named triplet: cluster + user + namespace. Switching context changes which cluster kubectl targets next β it is safe and instant.
kubeconfig βββ clusters: [dev-cluster, prod-cluster, local] βββ users: [dev-admin, prod-admin, minikube] βββ contexts: β βββ dev β dev-cluster + dev-admin + namespace: default β βββ prod β prod-cluster + prod-admin + namespace: production β βββ local β local + minikube + namespace: default βββ current-context: dev β kubectl uses this
Output Formats
| Flag | Use case |
|---|---|
-o wide | Extra columns (Node IP, etc.) |
-o yaml | Full resource as YAML |
-o json | Full resource as JSON |
-o jsonpath='{.metadata.name}' | Extract a specific field |
-o name | Just resource names (scripting) |
Merging Multiple kubeconfigs
When you receive credentials for a new cluster (from AWS EKS, GKE, kubeadm, etc.) you get a separate kubeconfig. Merge it safely:
KUBECONFIG=~/.kube/config:~/new-cluster.yaml \ kubectl config view --merge --flatten > ~/.kube/merged.yaml mv ~/.kube/merged.yaml ~/.kube/config
Alternatively, use the KUBECONFIG env var to temporarily target a specific file:
KUBECONFIG=~/project.yaml kubectl get pods
Productivity Tips
alias k=kubectl alias kgp='kubectl get pods' alias kns='kubectl config set-context --current --namespace' # Install kubectx/kubens for one-word context/namespace switching brew install kubectx kubectx prod # switch context kubens production # switch namespace