Basic Bash – Answers
Solutions to the 20 CKA practice questions.
Answer 1: Extract Pod Names from Specific Namespace
bash
# Method 1: Using awk
kubectl get pods -n kube-system --no-headers | awk '{print $1}'
# Method 2: Using jsonpath
kubectl get pods -n kube-system -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n'
# Method 3: Using custom-columns
kubectl get pods -n kube-system -o custom-columns=:metadata.name --no-headersAnswer 2: Count Running Pods
bash
# Method 1: grep + wc
kubectl get pods -A | grep Running | wc -l
# Method 2: awk with count
kubectl get pods -A --no-headers | awk '$3=="Running"' | wc -l
# Method 3: field-selector
kubectl get pods -A --field-selector=status.phase=Running --no-headers | wc -lAnswer 3: Find Pods on Specific Node
bash
# Method 1: Using field-selector (fastest)
kubectl get pods -A --field-selector=spec.nodeName=worker-1 -o custom-columns=:metadata.name --no-headers
# Method 2: Using jsonpath
kubectl get pods -A -o jsonpath='{.items[?(@.spec.nodeName=="worker-1")].metadata.name}' | tr ' ' '\n'
# Method 3: Using awk with -o wide
kubectl get pods -A -o wide | awk '$8=="worker-1" {print $2}'Answer 4: Extract Container Images
bash
# Method 1: JSONPath with tr + sort + uniq
kubectl get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort -u
# Method 2: Using nested range in jsonpath
kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' | sort -uAnswer 5: Filter Pods by Label
bash
# Using label selector + custom columns
kubectl get pods -l app=nginx -o custom-columns=NAME:.metadata.name,IP:.status.podIP --no-headers
# Alternative: JSONPath
kubectl get pods -l app=nginx -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.status.podIP}{"\n"}{end}'Answer 6: Decode Secret Value
bash
# One-liner
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d
# With echo for newline
kubectl get secret db-creds -o jsonpath='{.data.password}' | base64 -d && echoAnswer 7: Find Failed Pods
bash
# Method 1: grep -v (exclude Running and Completed)
kubectl get pods -A | grep -v "Running\|Completed" | awk 'NR>1 {printf "%-20s %-30s %s\n", $1, $2, $4}'
# Method 2: awk with condition
kubectl get pods -A --no-headers | awk '$4!="Running" && $4!="Completed" {printf "%-20s %-30s %s\n", $1, $2, $4}'Answer 8: Extract Node Internal IPs
bash
# Using JSONPath filter
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}' | tr ' ' '\n'
# Alternative: using range
kubectl get nodes -o jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'Answer 9: Count Pods Per Namespace
bash
# Using awk with associative array and sort
kubectl get pods -A --no-headers | awk '{count[$1]++} END {for (ns in count) print count[ns], ns}' | sort -rn
# Alternative: using uniq -c
kubectl get pods -A --no-headers | awk '{print $1}' | sort | uniq -c | sort -rnAnswer 10: Modify Deployment Replicas (File Edit)
bash
# Using sed with backup
sed -i.bak 's/replicas: 3/replicas: 5/' deployment.yaml
# Verify
grep replicas deployment.yaml
# Alternative: in-place without backup (risky!)
sed -i 's/replicas: 3/replicas: 5/' deployment.yamlAnswer 11: Extract Events for Failing Pod
bash
# Using sed to extract Events section, then tail
kubectl describe pod failing-pod | sed -n '/Events:/,$p' | tail -n 11
# Alternative: grep with context
kubectl describe pod failing-pod | grep -A 10 "^Events:"Answer 12: Find Largest Log File
bash
# Using find + sort
find /var/log -type f -name "*.log" -exec ls -lh {} \; | sort -k5 -hr | head -1
# Alternative: using du
find /var/log -type f -name "*.log" -exec du -h {} \; | sort -hr | head -1Answer 13: Get Pod Resource Requests
bash
# Using jsonpath
kubectl get pod web-app -o jsonpath='CPU: {.spec.containers[0].resources.requests.cpu} Memory: {.spec.containers[0].resources.requests.memory}'
# With echo for newline
kubectl get pod web-app -o jsonpath='CPU: {.spec.containers[0].resources.requests.cpu} Memory: {.spec.containers[0].resources.requests.memory}' && echoAnswer 14: List Pods Sorted by Age
bash
# Using sort -k (column 5 is AGE)
kubectl get pods -A | sort -k5
# More accurate: using jsonpath with creation timestamp
kubectl get pods -A -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,AGE:.metadata.creationTimestamp | sort -k3Answer 15: Batch Delete Pods by Pattern
bash
# Using for loop
for pod in $(kubectl get pods -o name | grep "test-"); do
kubectl delete $pod
done
# Alternative: one-liner
kubectl get pods -o name | grep "test-" | xargs kubectl delete
# With confirmation
kubectl delete pods $(kubectl get pods -o name | grep "test-" | cut -d'/' -f2)Answer 16: Extract ConfigMap Keys
bash
# Using jsonpath to get keys
kubectl get configmap app-config -o jsonpath='{.data}' | jq -r 'keys[]'
# Without jq (if available):
kubectl get configmap app-config -o jsonpath='{range .data}{@}{"\n"}{end}' | cut -d':' -f1
# Alternative: Using go-template
kubectl get configmap app-config -o go-template='{{range $k, $v := .data}}{{$k}}{{"\n"}}{{end}}'Answer 17: Find Pods Using Specific Image
bash
# Using jsonpath filter
kubectl get pods -A -o jsonpath='{range .items[?(@.spec.containers[*].image=="nginx:1.19")]}{.metadata.namespace}{" "}{.metadata.name}{"\n"}{end}'
# Alternative: grep on wide output
kubectl get pods -A -o wide | grep "nginx:1.19" | awk '{print $2, $1}'Answer 18: Monitor Log File for Errors
bash
# Using tail -f with grep
tail -f /var/log/app.log | grep ERROR
# Alternative: with color highlighting
tail -f /var/log/app.log | grep --color=always ERRORAnswer 19: Export Running Pod YAML
bash
# Get YAML and remove status/managed fields
kubectl get pod api-server -o yaml | \
kubectl neat > api-server-clean.yaml
# Without kubectl-neat (manual sed):
kubectl get pod api-server -o yaml | \
sed '/^ uid:/d' | \
sed '/^ resourceVersion:/d' | \
sed '/^ creationTimestamp:/d' | \
sed '/^status:/,$ d' > api-server-clean.yaml
# Simplest: dry-run recreate
kubectl get pod api-server -o yaml | \
kubectl create --dry-run=client -o yaml -f - > api-server-clean.yamlAnswer 20: Calculate Total CPU Requests
bash
# Using awk to sum CPU values
kubectl get pods -n production -o jsonpath='{range .items[*]}{.spec.containers[*].resources.requests.cpu}{"\n"}{end}' | \
sed 's/m$//' | \
awk '{sum += $1} END {print sum "m"}'
# More robust: handle both millicores (m) and cores
kubectl get pods -n production -o json | \
jq -r '.items[].spec.containers[].resources.requests.cpu' | \
sed 's/m$//' | \
awk '{
if ($1 ~ /[0-9]+$/) sum += $1 * 1000
else sum += $1
} END {print sum "m"}'Pro Tips
- Always test with
| headfirst before running full commands - Use
--no-headersto avoid counting header lines - Prefer field-selector over grep when available (faster)
- Quote variables in scripts:
"$VAR"not$VAR - Use
-o namefor resource-prefixed output:pod/nginx - Combine tools:
kubectl ... | grep ... | awk ... | sort - Save complex commands as shell functions or aliases
- Remember
tr ' ' '\n'to split space-separated values to lines