6.08 KubeConfig in Kubernetes
π― What is KubeConfig?
KubeConfig is a YAML configuration file used by kubectl to:
- Connect to Kubernetes API Server
- Authenticate using client certificates
- Select cluster, user, and namespace context
Without kubeconfig, you would need to run:
kubectl get pods \
--server https://my-kube-playground:6443 \
--client-key admin.key \
--client-certificate admin.crt \
--certificate-authority ca.crt
KubeConfig eliminates this repetition.
π Default Location
Override with:
π§© KubeConfig Structure
A kubeconfig file contains three main sections:
| Section | Purpose |
|---|---|
| clusters | API server endpoints |
| users | Authentication credentials |
| contexts | Link user + cluster (+ namespace) |
π Basic Example
apiVersion: v1
kind: Config
clusters:
- name: my-kube-playground
cluster:
certificate-authority: /etc/kubernetes/pki/ca.crt
server: https://my-kube-playground:6443
users:
- name: my-kube-admin
user:
client-certificate: /etc/kubernetes/pki/users/admin.crt
client-key: /etc/kubernetes/pki/users/admin.key
contexts:
- name: my-kube-admin@my-kube-playground
context:
cluster: my-kube-playground
user: my-kube-admin
namespace: default
current-context: my-kube-admin@my-kube-playground
π How Context Works
Context binds:
- Cluster
- User
- Namespace (optional)
Switch context:
View current config:
π¦ Multiple Clusters Example
- development
- production
- my-kube-playground
- admin
- dev-user
- prod-user
- admin@production
- dev@google
- prod-user@production
π Namespaces in Context
You can define namespace per context:
Now:
Automatically runs in finance namespace.
π Certificates in KubeConfig
Two ways to define CA:
Option 1: File Path
Option 2: Embedded (Base64)
Encode certificate:
Decode:
π‘ Production Best Practices
β DO
Success
- Restrict kubeconfig file permissions (600)
- Use separate kubeconfig per environment
- Rotate certificates regularly
- Use short-lived client certificates
- Store production kubeconfigs securely
- Use RBAC to limit privileges
β DON'T
Danger
- Do NOT share admin kubeconfig publicly
- Do NOT commit kubeconfig to Git
- Do NOT embed long-lived credentials
- Do NOT use admin context for automation
- Do NOT mix production and dev contexts carelessly
π¨ Common Production Risks
| Issue | Risk |
|---|---|
| Stolen kubeconfig | Full cluster access |
| Wrong current-context | Deploy to wrong cluster |
| Expired client cert | kubectl failures |
| Embedded cert exposure | Secret leakage |
π Operational Commands
kubectl config get-contexts
kubectl config current-context
kubectl config use-context <name>
kubectl config set-context
kubectl config delete-context
π― Summary
- KubeConfig manages cluster access configuration
- Context links user + cluster (+ namespace)
- Supports multiple environments
- Handles client certificates
- Must be secured like a private key
Quote
A kubeconfig file is effectively your cluster access passport β protect it like root credentials.