Using Advanced kubectl Techniques
1. Using JSONPath Queries
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.capacity.cpu}{"\n"}{end}'
2. Using Custom Columns
kubectl get pods -o custom-columns=\
NAME:.metadata.name,\
NODE:.spec.nodeName,\
STATUS:.status.phase,\
IP:.status.podIP
3. Formatting Output
| -o flag | Use |
|---|---|
| yaml / json | Full spec |
| wide | Extended columns |
| name | Only resource names |
| jsonpath / go-template | Scripted extraction |
| custom-columns-file | Reusable column spec |
4. Using Field Selectors
kubectl get pods --field-selector status.phase=Running
kubectl get events --field-selector type=Warning,involvedObject.kind=Pod
5. Using Label Selectors
kubectl get pods -l 'app=web,tier=frontend'
kubectl get pods -l 'env in (prod,stage),!canary'
6. Performing Bulk Operations
kubectl delete pods -l app=tmp
kubectl get pods -A -l app=web -o name | xargs -I{} kubectl restart {}
kubectl annotate pods --all owner=platform --overwrite
7. Using kubectl patch
kubectl patch deploy web --type=merge -p '{"spec":{"replicas":5}}'
kubectl patch deploy web --type=json \
-p '[{"op":"replace","path":"/spec/template/spec/containers/0/image","value":"nginx:1.27"}]'
kubectl patch deploy web --type=strategic -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.27"}]}}}}'
| --type | Format |
|---|---|
| strategic | K8s strategic merge (default) |
| merge | RFC 7396 JSON merge |
| json | RFC 6902 JSON patch ops |
8. Creating Resources from stdin
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ConfigMap
metadata: { name: from-stdin }
data: { key: value }
EOF
9. Using kubectl diff
kubectl diff -f manifest.yaml
KUBECTL_EXTERNAL_DIFF=meld kubectl diff -k overlays/prod
10. Using kubectl wait
kubectl wait --for=condition=Ready pod/web --timeout=120s
kubectl wait --for=jsonpath='{.status.phase}'=Running pod/web
kubectl wait --for=delete pod/old --timeout=60s
kubectl rollout status deploy/web --timeout=5m
11. Creating Dry Runs
| Mode | Effect |
|---|---|
--dry-run=client | Local validation |
--dry-run=server | API-validated; runs admission webhooks |
12. Using kubectl explain
kubectl explain pod.spec.containers.resources
kubectl explain deploy --recursive
kubectl explain ingress.spec.rules --api-version=networking.k8s.io/v1