Skip to main content
Course/Foundation/kubectl & kubeconfig
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 context

Contexts: 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

FlagUse case
-o wideExtra columns (Node IP, etc.)
-o yamlFull resource as YAML
-o jsonFull resource as JSON
-o jsonpath='{.metadata.name}'Extract a specific field
-o nameJust 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