Working with Contexts and Kubeconfig

1. Viewing Current Context

CommandOutput
kubectl config current-contextActive context name
kubectl config view --minifyActive context details only

2. Listing All Contexts

kubectl config get-contexts
kubectl config get-contexts -o name
ColumnMeaning
CURRENT* marks active context
NAMEContext name
CLUSTERReferenced cluster entry
AUTHINFOReferenced user entry
NAMESPACEDefault namespace

3. Switching Contexts

CommandAction
kubectl config use-context stagingSwitch
kubectx stagingPlugin shortcut
kubectx -Toggle previous context

4. Creating New Context

kubectl config set-cluster prod \
  --server=https://api.prod:6443 --certificate-authority=ca.crt
kubectl config set-credentials alice \
  --client-certificate=alice.crt --client-key=alice.key
kubectl config set-context prod-alice \
  --cluster=prod --user=alice --namespace=payments
StepPurpose
set-clusterServer URL + CA
set-credentialsUser auth
set-contextCombine cluster + user + ns

5. Renaming Contexts

CommandAction
kubectl config rename-context OLD NEWRename in-place
kubectx NEW=OLDPlugin equivalent

6. Deleting Contexts

CommandAction
kubectl config delete-context NAMERemove context entry
kubectl config delete-cluster NAMERemove cluster entry
kubectl config delete-user NAMERemove user entry

7. Setting Context Namespace

kubectl config set-context --current --namespace=payments
kubectl config set-context prod-alice --namespace=audit
FlagEffect
--currentModify active context only

8. Merging Kubeconfig Files

KUBECONFIG=~/.kube/config:~/.kube/prod-config \
  kubectl config view --flatten > ~/.kube/merged
mv ~/.kube/merged ~/.kube/config
MechanismBehavior
KUBECONFIG envColon-separated list; merges in order
--flattenInline cert/key data
Conflict resolutionFirst occurrence wins

9. Viewing Kubeconfig Content

CommandOutput
kubectl config viewSanitized (cert data redacted)
kubectl config view --rawIncludes sensitive data
kubectl config view --minify -o yamlJust active context

10. Setting Cluster Server

kubectl config set-cluster prod \
  --server=https://api.prod.example.com:6443 \
  --certificate-authority=/etc/k8s/ca.crt \
  --embed-certs=true
FlagPurpose
--serverAPI endpoint URL
--certificate-authorityServer CA path
--embed-certs=trueInline base64 CA
--insecure-skip-tls-verify=trueSkip TLS (dev only)

11. Setting User Credentials

AuthFlags
Cert--client-certificate, --client-key
Token--token=TOKEN
Basic--username --password DEPRECATED
Exec pluginusers[].user.exec.{command,args,env}

Example: AWS EKS exec auth

users:
- name: arn:aws:eks:us-east-1:111:cluster/prod
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: aws
      args: ["eks", "get-token", "--cluster-name", "prod"]