{ "id": "field-selector-basics", "title": "Filtering Resources with Field Selectors", "category": "Core Concepts", "difficulty": "Easy", "type": "task", "weight": 4, "description": "## Filtering Resources with Field Selectors\n\nField selectors let you filter Kubernetes resources by the **value of specific object fields** — similar to how label selectors work but targeting any field in the resource spec or status.\n\nCommon use cases:\n- Find all pods in a specific phase: `kubectl get pods --field-selector=status.phase=Running`\n- Find resources in a specific namespace: `kubectl get pods --field-selector=metadata.namespace=kube-system`\n\n**Your task:**\n\nSeveral pods have been created for you — some Running, some in a Failed state.\n\n1. Use a field selector to list only the **Running** pods and count them. Save the count to `/tmp/running-count.txt`\n2. Use a field selector to list all pods **not** in the `default` namespace (filter by `metadata.namespace!=default`)\n\n```bash\n# Count running pods:\nkubectl get pods --field-selector=status.phase=Running --no-headers | wc -l\n```", "hints": [ { "title": "Field selector syntax", "body": "Use `--field-selector=field.path=value` to filter. Multiple conditions are comma-separated. Supported operators: `=`, `==`, `!=`.", "command": "kubectl get pods --field-selector=status.phase=Running" }, { "title": "Save running pod count to a file", "body": "Pipe the result through wc -l and redirect to the file.", "command": "kubectl get pods --field-selector=status.phase=Running --no-headers | wc -l | tr -d ' ' > /tmp/running-count.txt" } ], "setup_commands": [ { "command": "kubectl run alpha --image=nginx:alpine 2>/dev/null || true" }, { "command": "kubectl run beta --image=nginx:alpine 2>/dev/null || true" }, { "command": "kubectl run crash-pod --image=busybox:1.36 --restart=Never -- /bin/false 2>/dev/null || true" }, { "command": "kubectl rollout status deployment/alpha --timeout=30s 2>/dev/null || true" } ], "validation": { "commands": [ { "description": "File /tmp/running-count.txt exists and has a numeric value", "command": "cat /tmp/running-count.txt", "expected_output": "^[0-9]+$", "match": "regex" }, { "description": "The saved count matches the actual number of Running pods", "command": "LIVE=$(kubectl get pods --field-selector=status.phase=Running --no-headers 2>/dev/null | wc -l | tr -d ' '); SAVED=$(cat /tmp/running-count.txt 2>/dev/null | tr -d ' '); [ \"$LIVE\" = \"$SAVED\" ] && echo 'match' || echo 'mismatch'", "expected_output": "match", "match": "exact" } ] }, "default_namespace": "default", "teardown_commands": [ { "command": "kubectl delete pod alpha beta crash-pod --ignore-not-found --grace-period=0 --force" }, { "command": "rm -f /tmp/running-count.txt" } ] }