Scripting Patterns with kubectl
kubectl becomes even more powerful when combined with standard Unix tools. These patterns are essential for automation, bulk operations, and custom reporting.
Piping to jq
jq is the standard tool for processing JSON output:
# Get all container images across the cluster
kubectl get pods -A -o json | jq -r '.items[].spec.containers[].image' | sort -u
# Get pods with their restart counts
kubectl get pods -o json | jq -r '.items[] | "\(.metadata.name) \(.status.containerStatuses[0].restartCount)"'
# Find pods using more than 500Mi memory in requests
kubectl get pods -o json | jq -r '.items[] | select(.spec.containers[].resources.requests.memory) | .metadata.name'
xargs Patterns
Use xargs to feed kubectl output into other commands:
# Delete all completed pods
kubectl get pods --field-selector=status.phase==Succeeded -o name | xargs kubectl delete
# Describe all pods with a specific label
kubectl get pods -l app=web -o name | xargs -I {} kubectl describe {}
# Get logs from all pods matching a label
kubectl get pods -l app=web -o name | xargs -I {} kubectl logs {}
Bash Loops
For more control, iterate with a for loop:
# Restart all deployments in a namespace
for deploy in $(kubectl get deploy -n staging -o name); do
kubectl rollout restart "$deploy" -n staging
done
# Check image versions across namespaces
for ns in dev staging prod; do
echo "=== $ns ==="
kubectl get pods -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[0].image}{"\n"}{end}'
done
kubectl with awk
awk is useful for filtering and reformatting tabular output:
# Get pods with high restart counts (more than 5)
kubectl get pods | awk '$4 > 5 {print $1, $4}'
# Sum total restarts across all pods
kubectl get pods | awk 'NR>1 {sum+=$4} END {print "Total restarts:", sum}'
# Find pods not in Running state
kubectl get pods | awk '$3 != "Running" && NR>1 {print $1, $3}'
Combining Tools
# Export all ConfigMaps as individual YAML files
for cm in $(kubectl get cm -o name); do
name=$(echo "$cm" | cut -d/ -f2)
kubectl get "$cm" -o yaml > "${name}.yaml"
done
Key Takeaways
- Use
-o jsonwithjqfor complex field extraction and filtering xargsturns kubectl output into input for other kubectl commands- Bash loops offer full control for multi-step operations
awkexcels at filtering and aggregating tabular kubectl output