Working with Contexts and Kubeconfig
1. Viewing Current Context
| Command | Output |
kubectl config current-context | Active context name |
kubectl config view --minify | Active context details only |
2. Listing All Contexts
kubectl config get-contexts
kubectl config get-contexts -o name
| Column | Meaning |
| CURRENT | * marks active context |
| NAME | Context name |
| CLUSTER | Referenced cluster entry |
| AUTHINFO | Referenced user entry |
| NAMESPACE | Default namespace |
3. Switching Contexts
| Command | Action |
kubectl config use-context staging | Switch |
kubectx staging | Plugin 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
| Step | Purpose |
| set-cluster | Server URL + CA |
| set-credentials | User auth |
| set-context | Combine cluster + user + ns |
5. Renaming Contexts
| Command | Action |
kubectl config rename-context OLD NEW | Rename in-place |
kubectx NEW=OLD | Plugin equivalent |
6. Deleting Contexts
| Command | Action |
kubectl config delete-context NAME | Remove context entry |
kubectl config delete-cluster NAME | Remove cluster entry |
kubectl config delete-user NAME | Remove user entry |
7. Setting Context Namespace
kubectl config set-context --current --namespace=payments
kubectl config set-context prod-alice --namespace=audit
| Flag | Effect |
--current | Modify active context only |
8. Merging Kubeconfig Files
KUBECONFIG=~/.kube/config:~/.kube/prod-config \
kubectl config view --flatten > ~/.kube/merged
mv ~/.kube/merged ~/.kube/config
| Mechanism | Behavior |
| KUBECONFIG env | Colon-separated list; merges in order |
| --flatten | Inline cert/key data |
| Conflict resolution | First occurrence wins |
9. Viewing Kubeconfig Content
| Command | Output |
kubectl config view | Sanitized (cert data redacted) |
kubectl config view --raw | Includes sensitive data |
kubectl config view --minify -o yaml | Just 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
| Flag | Purpose |
--server | API endpoint URL |
--certificate-authority | Server CA path |
--embed-certs=true | Inline base64 CA |
--insecure-skip-tls-verify=true | Skip TLS (dev only) |
11. Setting User Credentials
| Auth | Flags |
| Cert | --client-certificate, --client-key |
| Token | --token=TOKEN |
| Basic | --username --password DEPRECATED |
| Exec plugin | users[].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"]