The API and the loopLesson 4 of 8
- Desired state and the reconcile loop, not reconciled
- Control plane and nodes, not reconciled
- API machinery: groups, versions and resource versions, not reconciled
- kubectl and kubeconfig, not reconciled
- Namespaces, labels and annotations, not reconciled
- Declarative management and server-side apply, not reconciled
- Owners, finalizers and garbage collection, not reconciled
- Custom resources and operators, not reconciled
kubectl and kubeconfig
kubectl finds its cluster, identity and namespace in kubeconfig, reads objects in whatever shape you ask for, and can show a change before making it. Know which context a command uses before you run it.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
kubectl is an API client with opinions. Before it sends a single request it has to answer three questions: which cluster, as whom, and in which namespace. The answers live in kubeconfig, and most “it worked on my machine” moments with Kubernetes come down to a different answer to one of them. This lesson covers how kubectl finds those answers, then how to read and change objects precisely once it has them.
Reconcile, in 8 scenes
kubeconfig anatomy
A kubeconfigA YAML file of clusters, users and contexts that tells kubectl and other API clients where the API server is and how to authenticate to it. Any file in this format is a kubeconfig file, whatever its name. file has three lists and a pointer:
clustersname API servers: aserverURL and the certificate authority used to verify it.usersname credentials: a client certificate, a token, or a command that produces one.contextsname combinations of one cluster, one user and an optional default namespace.current-contextnames the context kubectl uses when you do not pass one.
kind writes one of each for kx, all called kind-kx:
kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: DATA+OMITTED
server: https://127.0.0.1:39629
name: kind-kx
contexts:
- context:
cluster: kind-kx
user: kind-kx
name: kind-kx
current-context: kind-kx
kind: Config
preferences: {}
users:
- name: kind-kx
user:
client-certificate-data: DATA+OMITTED
client-key-data: DATA+OMITTEDkubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * kind-kx kind-kx kind-kx
config view hides secrets as DATA+OMITTED; --raw prints them, so keep that output out of tickets and chat. --minify trims the view to the current context, which is the quickest way to see exactly what a command will use. The server address is a port on your own machine because kind publishes the API server of its control-plane container there.
The names matter less than the references. A context points at a cluster and a user by name, so one user entry can serve several clusters, or one cluster can be reached with several identities. A “user” here is only a label for a credential. Kubernetes has no User objects; the API server learns who you are from the credential on each request and never sees your kubeconfig.
Merging and switching
kubectl decides which kubeconfig files to read in a fixed order:
- If
--kubeconfigis set, use that one file and merge nothing. - Otherwise, if the
KUBECONFIGenvironment variable is set, merge the files it lists, separated by colons (semicolons on Windows). - Otherwise, read
$HOME/.kube/config.
When merging, the first file to set a value or a map key wins, and later files never change it. That applies to current-context, and to entries with the same name: if two files both define a user called admin, kubectl uses only the first file’s admin, discarding even non-conflicting fields from the second. File paths inside a kubeconfig, such as certificate-authority: ca.crt, are resolved relative to the kubeconfig file, not to your working directory.
The context comes from --context if you pass it, and otherwise from the merged current-context. The namespace comes from -n if you pass it, then from the context, then defaults to default.
kubectl create namespace shop
namespace/shop created
kubectl config set-context --current --namespace=shop
Context "kind-kx" modified.
kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE * kind-kx kind-kx kind-kx shop
kubectl get pods
No resources found in shop namespace.
kubectl config use-context NAME rewrites current-context, and set-context NAME --cluster=… --user=… --namespace=… creates or edits a context. Both write to a file, so the change outlives your shell.
Credentials
The user entry tells kubectl how to prove an identity. The common forms:
- Client certificate. kubectl presents a certificate signed by a CA the API server trusts. The certificate’s common name becomes the username and its organisations become groups. kind uses this, so it is what kx shows.
- Bearer token. A static
tokenfield, often a ServiceAccount token for automation. Anyone holding it is that identity until it expires or is revoked. - Exec credential plugin. kubectl runs a command and uses the token it prints. Cloud providers and single sign-on tools work this way.
kubectl auth whoami
ATTRIBUTE VALUE Username kubernetes-admin Groups [kubeadm:cluster-admins system:authenticated]
kubectl auth whoami asks the API server how it authenticated the request, which settles arguments about which identity a kubeconfig really carries. The group kubeadm:cluster-admins is bound to cluster-admin, so this identity can do anything.
exec credential pluginA program named in a kubeconfig user entry that kubectl runs to obtain a short-lived credential, which it reads from the program’s output as an ExecCredential object. are stable since Kubernetes 1.22. The user entry names the program and how to run it:
users:
- name: dev-sso
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: example-login
args: ["token", "--cluster", "dev"]
env:
- name: LOGIN_PROFILE
value: dev
installHint: Install example-login from your team's tool catalog.
provideClusterInfo: false
interactiveMode: IfAvailable
kubectl runs example-login token --cluster dev with that extra environment variable and reads an ExecCredential from standard output, whose status.token it sends as a bearer token. If the output includes status.expirationTimestamp, kubectl caches the token until then, or until the API server answers 401. interactiveMode says whether the plugin may prompt on the terminal (Never, IfAvailable or Always), and installHint is printed when the command is missing.
Reading objects
kubectl get lists objects in a table chosen for that kind, but its output is a view of JSON objects, and you can ask for exactly the view you need:
| Flag | Gives you |
|---|---|
-o wide | The default table plus extra columns, such as node and IP for pods |
-o yaml, -o json | The full object as stored, status included |
-o name | type/name per line, ready to pipe into another command |
-o custom-columns=… | A table of the fields you name |
-o jsonpath=… | Just the fields you name, formatted as you like |
--sort-by=… | The rows sorted by a JSONPath field |
-l, --field-selector | Only objects whose labels or fields match |
kubectl get pods --sort-by=.spec.nodeName -o custom-columns=NAME:.metadata.name,NODE:.spec.nodeName,IP:.status.podIP
NAME NODE IP web-89c8ffd94-pggpj kx-worker 10.244.1.3 web-89c8ffd94-nshlv kx-worker2 10.244.2.2 web-89c8ffd94-dq87d kx-worker3 10.244.3.2
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}'
web-89c8ffd94-dq87d kx-worker3 web-89c8ffd94-nshlv kx-worker2 web-89c8ffd94-pggpj kx-worker
kubectl get deploy web -o jsonpath='{.spec.template.spec.containers[0].image}'
nginx:1.30
Custom columns suit people; JSONPath suits scripts, because it prints nothing but the values. --sort-by orders the rows by any field; without it, kubectl prints them in the order the API server returns them. A list’s objects are under .items, which is why the range expression iterates .items[*]. Filters work too: {.status.conditions[?(@.type=="Ready")].status} picks one condition by type. Kubernetes 1.37 also makes KYAML stable, a stricter YAML style that avoids YAML’s ambiguous scalars, printed with -o kyaml.
kubectl describe is a different tool: it joins an object with related information, most usefully its recent events, into prose for people. Use get -o yaml when you need the object’s exact fields, and describe when you need to know why it is in that state. kubectl get --watch streams changes using the list-and-watch protocol from the previous lesson.
Writing objects
kubectl offers two styles of change. Imperative commands state an action: create, delete, scale, label, annotate, set image, patch, edit. Each takes effect at once, is quick at a terminal, and leaves no record of intent except the object itself. patch changes only the fields you name, and edit opens the live object in your editor and sends what you changed. Declarative management states the result: you keep manifests in files, usually in version control, and kubectl apply -f makes the cluster match them, creating, updating or leaving each object alone as needed. The files become the record of what should exist, which is what reviews, rollbacks and GitOps tools rely on.
The two styles meet on the same objects, which is where surprises come from. Scale a Deployment by command after applying it, and the manifest no longer describes the cluster; the next apply resets the replica count. Server-side apply makes that ownership explicit by recording which manager owns each field, which the declarative management lesson covers in depth.
Every write, imperative or declarative, uses the concurrency rules from the previous lesson. kubectl edit sends its change as a patch of only the fields you touched, with no resourceVersion, so it does not conflict when someone else changed the object while your editor was open: their changes to other fields survive, and your value wins on any field you both changed. If the API server rejects the edit as invalid, kubectl reopens the editor with the error at the top; if the write fails for another reason, it keeps your edit in a temporary file and suggests kubectl replace -f with that file.
kubectl delete removes an object, and its --cascade flag decides what happens to the objects it owns. The default, background, deletes the owner at once and lets the garbage collector remove its dependents afterwards; foreground removes the dependents before the owner; orphan leaves them in place with no owner.
Dry runs and diffs
Two kinds of dry run answer different questions. --dry-run=client builds the object locally and never contacts the server, which makes it a generator, not a test: it catches typos in flags and little else. --dry-run=server sends the real request with dryRun=All. The API server runs authentication, authorization, mutating and validating admission, defaulting and validation, then skips the write to etcd and returns the object it would have stored. cache.yaml in this lesson’s working directory holds a Deployment the cluster does not have:
kubectl apply -f cache.yaml --dry-run=server
deployment.apps/cache created (server dry run)
kubectl get deployment cache
Error from server (NotFound): deployments.apps "cache" not found
kubectl diff -f goes one step further: it performs a server dry run of the apply and compares the result with the live object, so you see exactly what apply would change, defaults and admission mutations included. This lesson’s web was applied from web.yaml, which says three replicas. Here someone scales it to five by hand:
kubectl scale deployment web --replicas=5
deployment.apps/web scaled
kubectl diff -f web.yaml
diff -u -N /tmp/LIVE-4598894692/apps.v1.Deployment.default.web /tmp/MERGED-9853932845/apps.v1.Deployment.default.web
--- /tmp/LIVE-4598894692/apps.v1.Deployment.default.web 2026-11-19 09:01:00.000000000 +0000
+++ /tmp/MERGED-9853932845/apps.v1.Deployment.default.web 2026-11-19 09:01:00.000000000 +0000
@@ -15,7 +15,7 @@
uid: 85694271-5cb3-4bab-9fc4-fc111ace4711
spec:
progressDeadlineSeconds: 600
- replicas: 5
+ replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:Lines starting with - are live; lines starting with + are what apply would write. kubectl diff exits 0 when there is nothing to change, 1 when it found differences, and above 1 on errors, so in a script, exit code 1 is a result, not a failure. Set KUBECTL_EXTERNAL_DIFF to use a different diff program.
Generators and explain
Writing a manifest from memory is slow and error-prone. kubectl’s generators write the skeleton for you: kubectl create deployment, job, cronjob, configmap, secret, service, role, rolebinding and others build an object from flags, kubectl run builds a bare pod, and kubectl expose builds a Service for an existing workload. With --dry-run=client -o yaml they print the object instead of creating it:
kubectl create deployment cache --image=redis:8.8 --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: cache
name: cache
spec:
replicas: 1
selector:
matchLabels:
app: cache
strategy: {}
template:
metadata:
labels:
app: cache
spec:
containers:
- image: redis:8.8
name: redis
resources: {}
status: {}Redirect that into a file, delete the empty strategy, resources and status stubs, add what the generator has no flag for, and you have a manifest to apply and review.
To find out what a field means or which fields exist, kubectl explain reads the OpenAPI schema from the server, so it documents your cluster’s version and its CRDs:
kubectl explain deployment.spec.strategy
GROUP: apps
KIND: Deployment
VERSION: v1
FIELD: strategy <DeploymentStrategy>
DESCRIPTION:
The deployment strategy to use to replace existing pods with new ones.
DeploymentStrategy describes how to replace existing pods with new ones.
FIELDS:
rollingUpdate <RollingUpdateDeployment>
Rolling update config params. Present only if DeploymentStrategyType =
RollingUpdate.
type <string>
Type of deployment. Can be "Recreate" or "RollingUpdate". Default is
RollingUpdate.
Walk down the tree one field at a time, or add --recursive to see every field below a path at once.
kuberc preferences
kubeconfig holds where and who; it is a poor place for personal habits, because it is often generated, shared or replaced. kubercA kubectl preferences file, $HOME/.kube/kuberc by default, that holds command aliases and default flag values and never holds cluster details or credentials. holds those instead, and it is beta since Kubernetes 1.34. Point kubectl at another file with --kuberc or the KUBERC environment variable, and set KUBERC=off to ignore it while troubleshooting.
apiVersion: kubectl.config.k8s.io/v1beta1
kind: Preference
defaults:
- command: apply
options:
- name: server-side
default: "true"
- command: delete
options:
- name: interactive
default: "true"
aliases:
- name: getn
command: get
prependArgs:
- namespace
options:
- name: output
default: wide
defaults change what a command does when you do not pass a flag: here every apply is server-side and every delete asks for confirmation. A flag you type always wins over the default. aliases add commands: kubectl getn runs kubectl get namespace -o wide, and appendArgs adds arguments at the end. An alias cannot reuse the name of a built-in command.
In Kubernetes 1.35 and later, kuberc can also restrict exec credential plugins with credentialPluginPolicy, a beta field: AllowAll, DenyAll, or Allowlist with a credentialPluginAllowlist of permitted commands. That addresses the risk in the kubeconfig warning above. If you use a managed cluster, allow its plugin, such as aws for EKS, instead of denying all.
kubectl --context kind-kx config view --minifykubectl --context kind-kx auth whoamikubectl --context kind-kx create namespace shopkubectl --context kind-kx config set-context kind-kx --namespace=shopkubectl --context kind-kx get podskubectl --context kind-kx create deployment cache --image=redis:8.8 --dry-run=client -o yamlkubectl --context kind-kx config set-context kind-kx --namespace=defaultkubectl --context kind-kx delete namespace shop
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. These commands name the kind-kx context explicitly instead of using --current, so they change kind-kx even if your current context points somewhere else.
Actual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Switch clusters, users and namespaces with kubeconfig contexts without editing files by hand. (not yet met)
- Pull exactly the fields you need with -o yaml, jsonpath, custom-columns and --sort-by. (not yet met)
- Preview a change with --dry-run=server and kubectl diff before applying it. (not yet met)
- Scaffold a manifest with kubectl create ... --dry-run=client -o yaml. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 5. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig
- kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters
- kubernetes.io/docs/reference/access-authn-authz/authentication
- kubernetes.io/docs/reference/kubectl
- kubernetes.io/docs/reference/kubectl/jsonpath
- kubernetes.io/docs/reference/kubectl/kuberc
- kubernetes.io/docs/reference/kubectl/generated/kubectl_diff
- kubernetes.io/docs/reference/using-api/api-concepts
- kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers
- kubernetes.io/blog/2026/08/26/kubernetes-v1-37-release
- docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html
- docs.aws.amazon.com/eks/latest/userguide/access-entries.html
- docs.aws.amazon.com/eks/latest/userguide/cluster-endpoint.html
kubectl and kubeconfig
↓ ↑ step, 1 to 8 scene, Esc leave