Kubectl Cheat Sheet and Command Reference for Exams
AI-Generated Content
Kubectl Cheat Sheet and Command Reference for Exams
Mastering kubectl is non-negotiable for Kubernetes certification exams and daily DevOps work. Your ability to swiftly and accurately query, manage, and troubleshoot cluster resources under time pressure directly impacts your exam score and operational efficiency. This guide transforms you from a command-line novice to a proficient operator by building fluency in essential commands, output manipulation, and advanced techniques.
Foundational kubectl Commands for Resource Management
The core of kubectl proficiency lies in understanding a handful of verbs that allow you to interact with every Kubernetes object. You will use these commands constantly, both in exams and on the job.
The kubectl get command is your primary tool for listing resources. At its simplest, kubectl get pods shows all pods in the current namespace. For exams, you must know how to scope this: kubectl get pods -n kube-system lists pods in a specific namespace, while kubectl get pods --all-namespaces shows everything. To inspect a specific resource, use kubectl get pod my-pod -o yaml to see its full configuration. The kubectl describe command provides a consolidated, human-readable summary of a resource's state, events, and configuration. When a pod is failing, kubectl describe pod my-pod is often the fastest way to identify image pull errors, resource limits, or scheduling issues.
For troubleshooting, kubectl logs fetches the standard output from a container. Remember that you must specify the container name if the pod has more than one: kubectl logs my-pod -c my-container. The -f flag follows the log output in real-time, which is invaluable for debugging startup issues. To execute commands inside a running container, use kubectl exec. A common exam task is to use kubectl exec my-pod -- cat /etc/config.conf to verify a file's contents. For an interactive shell, you would use kubectl exec -it my-pod -- /bin/sh.
Resource management revolves around three key commands. kubectl apply is the declarative workhorse for creating and updating resources from a YAML or JSON file. You must understand that kubectl apply -f deployment.yaml will create the resource if it doesn't exist or patch it if it does, based on a calculated diff. To remove resources, use kubectl delete. You can delete by filename (kubectl delete -f deployment.yaml) or by type and name (kubectl delete pod my-pod). For quick edits, kubectl edit opens the live object's configuration in your default editor. For instance, kubectl edit deployment my-deploy lets you quickly change replica counts or image tags, but be cautious as this creates an imperative update.
Mastering Output Formatting for Efficient Analysis
Exams will test your ability to extract specific information quickly, moving beyond default table views. The default output of kubectl get is often insufficient for complex queries.
The -o wide flag provides wide output, adding columns like node names and IP addresses. For example, kubectl get pods -o wide is crucial for understanding pod scheduling. For machine-readable parsing or feeding data into other tools, JSON and YAML outputs are essential. Use kubectl get pod my-pod -o json or -o yaml. However, the real power comes from filtering these structured outputs. jsonpath allows you to query specific fields. The syntax is -o jsonpath='{.items[*].metadata.name}'. A classic exam use case is extracting all pod names: kubectl get pods -o jsonpath='{.items[*].metadata.name}'.
For creating custom, human-readable tables, use custom-columns. You define the column headers and the JSONPath to the data. For instance, to show pod names and their node assignments, you might run: kubectl get pods -o custom-columns="NAME:.metadata.name,NODE:.spec.nodeName". This skill is vital for answering questions that ask for a specific piece of data without extra clutter. Remember that you can combine these with sorting. To list pods sorted by restart count, you could use kubectl get pods -o custom-columns="NAME:.metadata.name,RESTARTS:.status.containerStatuses[0].restartCount" --sort-by='.status.containerStatuses[0].restartCount'.
Navigating Clusters and Namespaces with Precision
Kubernetes exams simulate multi-environment scenarios, requiring you to seamlessly switch contexts and namespaces. A context is a named set of cluster access parameters (user, cluster, namespace). You can view all contexts with kubectl config get-contexts and switch using kubectl config use-context my-context. A frequent exam pitfall is executing commands in the wrong cluster, so always verify your current context with kubectl config current-context.
Within a cluster, namespace management is key for isolating resources. Instead of repeatedly using the -n flag, you can set a default namespace for all subsequent commands in a context with kubectl config set-context --current --namespace=my-namespace. To see resources across all namespaces, always remember the -A or --all-namespaces flag. Furthermore, you must know common resource shortnames to save time. Shortnames are abbreviated aliases for resource types. For example, po for pods, deploy for deployments, svc for services, and ns for namespaces. Using kubectl get po is faster than kubectl get pods, and this efficiency is critical in timed exams.
Advanced Command Execution for Complex Operations
When you are unsure of a resource's structure, the kubectl explain command is your built-in reference manual. It provides the documentation for any Kubernetes resource or field. If you forget what fields are available in a pod's spec, run kubectl explain pod.spec. For nested fields, use the dotted path: kubectl explain pod.spec.containers. This is invaluable when writing or debugging YAML manifests during an exam, as it saves you from needing to memorize every field.
Chaining commands for complex operations is a high-yield skill. This often involves using kubectl get with jsonpath or custom-columns to generate arguments for another command. A practical scenario is updating the image for all pods in a deployment: you would typically edit the deployment spec with kubectl edit. But for chaining, you could extract a pod name and exec into it in one line using a subshell: kubectl exec -it __MATH_INLINE_0__()) is common for dynamic, script-like solutions.
Common Pitfalls
- Forgetting the Namespace Scope: The most common mistake is running
kubectl get podsand seeing no resources, because you are in the wrong namespace. Always double-check your current namespace withkubectl config view --minify | grep namespaceor explicitly use the-nflag. In exams, the question will specify the namespace to use; ignoring this will lead to wrong answers.
- Misusing Delete vs. Apply for Cleanup: If asked to "clean up" or "delete" resources created from a manifest, using
kubectl delete -f <file>is the correct, declarative method. Imperatively deleting resources by name (kubectl delete pod my-pod) might work but can leave related resources (like Services) orphaned, which may cost you points.
- Incorrect jsonpath or Custom-Column Syntax: When extracting fields, a typo in the JSONPath query will return empty results. Remember that
jsonpathuses curly braces and the item list for resources returns. For example, to get the first container's image from a pod, use{.spec.containers[0].image}, not{.spec.container.image}. Practice these queries beforehand.
- Overlooking Resource Shortnames and Aliases: In a time-crunched exam, typing out
kubectl get deploymentswastes seconds. Knowing and using shortnames likekubectl get deployis expected. Similarly, confusepo(pods) withpvc(persistentvolumeclaims) can lead to retrieving the wrong resource list.
Summary
- Core Command Fluency is Foundational: Achieve speed with
get,describe,logs,exec,apply,delete, andedit. These are your daily tools for inspection, troubleshooting, and management. - Output Formatting is a Force Multiplier: Master
-o wide,jsonpath, andcustom-columnsto extract precise data efficiently, a skill directly tested in performance-based exam tasks. - Context and Namespace Awareness is Critical: Always know your active cluster context and namespace. Use shortnames (
po,svc,deploy) and namespace flags (-n,-A) to navigate accurately and swiftly. - Leverage Explain and Chaining for Complexity: Use
kubectl explainas an in-command API reference. Chain commands using pipes,xargs, and command substitution ($()) to build powerful one-liners for complex operations. - Avoid Imperative Pitfalls in Declarative Exams: While chaining is powerful, prefer declarative methods (
apply -f,delete -f) when the exam task involves manifest files to ensure all resources are managed correctly.