Module 1.8: YAML for Kubernetes
Complexity:
[MEDIUM]Time to Complete: 60–90 minutes (long-form read)
Prerequisites: Modules 1.1-1.7, including basic Kubernetes resources, pods, services, deployments, labels, and the
kubectlworkflowCommand convention: Earlier commands are reference examples; check their files, names, permissions, and request scope before trying them in a disposable lab. Hands-on practice uses
yaml_checkafter setup in the same Bash terminal; the helper pins the request context and namespace and always uses server dry run.
What You’ll Be Able to Do
Section titled “What You’ll Be Able to Do”By the end of this module, you will be able to:
- Construct structurally sound Kubernetes manifests using YAML scalars, mappings, sequences, multi-line strings, and multi-document files.
- Deconstruct common Kubernetes manifest fields (
apiVersion,kind, andmetadata) and resource-specific payloads such as Deploymentspecor ConfigMapdata, so you can explain how documents become API objects. - Diagnose YAML syntax, schema, and type validation failures by combining dry-run output,
kubectl explain, and targeted inspection of nested manifest paths. - Design multi-resource application manifests that connect Deployments, Services, ConfigMaps, environment variables, labels, selectors, and volume mounts.
- Compare client-side validation, server-side validation, and diff workflows to choose the safest verification step before applying a production change.
Why This Module Matters
Section titled “Why This Module Matters”Hypothetical scenario: a financial platform prepares for a trading window with customer traffic already above its normal peak. A platform engineer reviews a routine Kubernetes manifest update: raise the replica count, adjust container arguments, and increase memory limits for the backend processors. An indentation mistake changes the container arguments from a sequence into a mapping. The YAML parser accepts the document, but Kubernetes validation rejects the malformed arguments structure. The team must inspect the data shape and repair the manifest before rollout.
The distinction matters during review: a parser can accept a mapping even when a particular Kubernetes field expects a sequence. Compare the field’s expected type with the structure produced by the indentation, then validate the corrected request. A visually plausible file is not enough to establish that its fields have the intended shapes.
The validation catch illustrates why YAML matters in Kubernetes. YAML is not just a convenient file format for humans; it is the front door to the API server’s declarative contract. A manifest is converted into structured data, validated, admitted through policy, persisted as desired state, and then reconciled by controllers. If the structure says the wrong thing, Kubernetes will faithfully pursue the wrong instruction or reject the request at the point where it can no longer interpret your intent. The discipline you build here is the discipline that keeps routine configuration work from becoming a production event.
Hypothetical scenario: a team rotates a TLS certificate through a Kubernetes Secret and uses YAML’s folded block scalar by mistake. The file is valid YAML, the Secret is created, and the rollout continues, but the folded scalar replaces certificate newlines with spaces. In this scenario the ingress controller rejects the altered PEM text and cannot load the certificate; another consumer may respond differently. A single character, > instead of |, does not break YAML syntax; it changes the application data that YAML carries, so a failure may appear later in the system.
This module teaches YAML as an operational interface, not as decorative syntax. You will learn the three YAML shapes that appear in every manifest, the four root fields Kubernetes uses to route objects, the schema tools that prevent guessing, and the validation workflow that turns manifest review into an engineering practice. The goal is not memorizing every field in Kubernetes 1.35; the goal is knowing how to reason from structure to schema to controller behavior when the cluster is about to act on your file. That reasoning gives reviewers something better than visual confidence: a repeatable path from text to API behavior.
1. YAML Fundamentals for Infrastructure
Section titled “1. YAML Fundamentals for Infrastructure”YAML is useful for configuration that people need to read and machines need to parse. JSON uses braces and quoted object-member names, with commas separating members. YAML can express nesting with indentation and less punctuation, a presentation some readers find easier to review. That choice also makes whitespace significant: the shape of each line helps the parser determine what belongs to what.
At the lowest level, YAML gives you three building blocks. A scalar is a single value such as nginx:1.27, 8080, true, or "production". A mapping is a collection of unique keys and values, the same idea as a dictionary or hash map in a programming language. A sequence is an ordered collection. In the block-style sequences used here, each item begins with a hyphen at the appropriate indentation level. Kubernetes resources combine these three shapes again and again until they describe a complete workload.
# This is a Mapping at the root levelserver: nginxport: 8080is_active: true # Boolean scalar
# This is a Sequence (List) of scalarsallowed_origins: - https://example.com - https://api.example.com
# This is a Mapping containing a Sequence of Mappingsusers: - name: alice role: admin permissions: - read - write - name: bob role: editor permissions: - readRead that example as a tree rather than as text. The root contains three mapping keys, server, port, and is_active, followed by two larger keys whose values contain nested structures. allowed_origins is a sequence of scalar strings, while users is a sequence of mappings, and each user mapping contains another sequence under permissions. Kubernetes uses this nesting style for fields like containers, env, and volumeMounts.
YAML indentation uses spaces, not tabs. The indentation width is a presentation choice; this lesson uses a consistent two-space style. Tabs are invalid as indentation, rather than merely a style disagreement. A one-space drift can change meaning without looking dramatic in a pull request, especially when a nested sequence item is visually close to the field above it. Configure your editor to show whitespace, convert tabs to spaces and use a consistent style before relying on visual review.
Pause and predict: in the users block above, how many items are in the users sequence, and what type of data does permissions hold?
Check your prediction
There are two user items, and each item is a mapping. The permissions value is a sequence of scalar strings. Counting hyphens at the same indentation level is the same habit you need when reviewing Kubernetes containers, ports, and env blocks.
Write the count and the type before you continue. The next section is about multi-line strings. It does not count the users items.
Multi-Line Strings: The | and > Operators
Section titled “Multi-Line Strings: The | and > Operators”YAML becomes especially useful in Kubernetes when you need to carry text that already has internal structure. ConfigMaps can contain application configuration files, shell scripts, or web server snippets. Secrets can contain certificate material, private key text, or configuration fragments whose line structure a consumer may depend on after decoding. JSON can represent that data, but it forces escaped newline characters into a single string, while YAML can embed the text in a readable block.
YAML has two block scalar operators that look similar and behave very differently. The literal block scalar, |, preserves ordinary line breaks; the folded block scalar, >, folds ordinary line breaks into spaces while preserving paragraph breaks around blank lines. The content indentation is removed, while additional indentation remains part of the content; chomping controls trailing line breaks. Check those details when exact text matters. Use | when the consumer needs the embedded line structure, such as in a script or certificate; > can be useful for a flowing description.
# Literal (|) - Preserves the script's line breaks in this examplesetup_script: | #!/bin/bash echo "Starting setup..." apt-get update apt-get install -y curl
# Folded (>) - Good for long descriptions that should be a single paragraphdescription: > This is a very long description that I want to type across multiple lines in my editor for readability, but I want the application to see it as a single, continuous string of text.The operational consequence is simple: choose the scalar based on what the application expects, not on what is easier to read in your editor. Use | for a shell script when its command lines need to remain separate. Use | to preserve the line structure of PEM certificate text: RFC 7468 specifies line-oriented boundaries and encoded data, while parser tolerance varies. A human-readable annotation that an external dashboard displays as a paragraph can use > because the consumer wants one flowing string.
Pause and predict: if you are embedding a .pem certificate key into a Kubernetes Secret, which operator must you use and why?
Check your prediction
Use the literal block scalar, |, to preserve the certificate’s line structure. If you use >, the manifest may pass YAML parsing while delivering altered text that a consumer may reject; parser tolerance varies. Compare the decoded value with the intended input.
Write the operator and the reason before you continue. The next section is about anchors. It does not name the certificate scalar.
Advanced YAML: Anchors (&) and Aliases (*)
Section titled “Advanced YAML: Anchors (&) and Aliases (*)”YAML anchors (&) and aliases (*) let one part of a document refer to another. An anchor names a reusable mapping or value; an alias refers to that anchored value elsewhere in the document. The merge key << comes from a YAML 1.1 working draft, not the YAML 1.2 core schema. Support depends on the parser: Kubernetes v1.35.0 vendors sigs.k8s.io/yaml v1.6.0 and go.yaml.in/yaml/v2 v2.4.3; check the parser your tool uses before relying on a merge. For larger reuse patterns, purpose-built templating tools may make the generated documents easier to inspect.
# Define an anchor named 'common_labels'base_labels: &common_labels app: web-tier environment: production managed-by: platform-team
frontend_pod: metadata: # Use the merge key (<<) to inject the alias <<: *common_labels name: react-frontend
backend_pod: metadata: <<: *common_labels name: node-apiWith a parser that supports merge keys, the alias is expanded into the resulting mapping before submission. A different parser can reject or interpret the extension differently. This distinction matters when debugging because validation concerns the resulting object shape, not an anchor as a special Kubernetes API field. The JSON below illustrates the intended expansion; inspect your tool’s output before using this technique in a shared repository. In a shared repository, explain the reuse pattern so reviewers do not have to guess where the keys came from.
{ "app": "web-tier", "environment": "production", "managed-by": "platform-team", "name": "react-frontend"}Pause and predict: after expansion, what does frontend_pod.metadata contain?
Check your prediction
With merge support, it contains the three shared keys plus name: react-frontend, as four siblings rather than a nested base_labels object.
Write the keys you expect before you continue. The next section is the manifest anatomy. It does not expand this alias.
2. The Anatomy of a Kubernetes Manifest
Section titled “2. The Anatomy of a Kubernetes Manifest”Once YAML gives you a data tree, Kubernetes needs to know what that tree represents. Every ordinary Kubernetes object starts with a small root-level contract: apiVersion, kind, metadata, and usually spec. Those fields are not decoration. They tell the API server which schema to use, which object type to route to, how to identify the object, and what desired state the controllers should reconcile. If the root contract is missing or contradictory, the cluster cannot safely interpret the manifest.
flowchart LR subgraph "Kubernetes Manifest Anatomy" A["apiVersion: apps/v1"] -.-> AD["1. Which API schema?"] B["kind: Deployment"] -.-> BD["2. What object type?"] C["metadata:<br> name: my-app<br> namespace: prod<br> labels: ..."] -.-> CD["3. Who am I?<br>(Identity & Routing)"] D["spec:<br> replicas: 3<br> template: ..."] -.-> DD["4. What do I want?<br>(Desired State)"] A ~~~ B B ~~~ C C ~~~ D end style A text-align:left style B text-align:left style C text-align:left style D text-align:leftThe apiVersion field selects the API group and version that define the resource schema. Core resources such as Pods, Services, ConfigMaps, and Secrets use v1; Deployments use apps/v1. The slash separates group from version rather than naming a file-system path. Operators can add custom resources with their own API groups and versions. Use discovery to check which group and version your target cluster serves instead of assuming an example from another cluster applies unchanged.
The kind field names the type of object inside that API version. Deployment, Service, Pod, Job, StatefulSet, and Ingress have different schemas and object-specific fields. Pairing kind: Deployment with apiVersion: v1 asks for a Deployment in the wrong group. Kubectl cannot map that group/version/kind through discovery and can report “no matches for kind” before submitting an object. Discovery requests may still reach the API server, so failure before object submission does not imply that no network request occurred.
The metadata field gives the object identity and the metadata that other controllers and tools use to find it. The name must be unique for that resource kind within a namespace. The namespace scopes names and policies, and omitting it means the object lands in the current or default namespace, depending on the command context. Labels are structured key-value pairs used by selectors, while annotations hold non-identifying metadata for tools, controllers, and humans. Treat labels as routing and grouping inputs, and treat annotations as descriptive or integration metadata unless a specific controller documents otherwise.
The spec field declares desired state, which is the central idea behind Kubernetes. A Deployment spec says how many replicas should exist, which pods it should manage, and what container template it should roll out. A Service spec says which ports to expose and which pod labels to select. A Pod spec says which containers, volumes, probes, and scheduling constraints should exist. Data-centric resources use different fields: ConfigMaps use data and binaryData, while Secrets use data and the write-only input stringData. They still follow the same object identity and API routing model.
Worked example: in Kubernetes 1.35, a Deployment belongs to apps/v1, and the pod template inside its spec contains the eventual container list. If you place image: nginx:1.27 directly under Deployment.spec, the YAML may still be valid, but the schema is wrong because the image field belongs under spec.template.spec.containers[]. This is the difference between YAML validity and Kubernetes validity. YAML only proves the text can become data; Kubernetes validation proves the data matches the chosen API schema.
Pause and predict: you are creating a ConfigMap, so which standard root field is replaced and what is the replacement called?
Check your prediction
A ConfigMap does not use a workload-style spec. It stores key-value content under data and optionally binaryData. You still need apiVersion, kind, and metadata, because the API server must know what object is being created and how to identify it.
Write the replaced field and its replacement before you continue. The next section is kubectl explain. It does not name this root field.
3. Exploring the Schema with kubectl explain
Section titled “3. Exploring the Schema with kubectl explain”You should not try to memorize the full Kubernetes API. Even the built-in resources have deeply nested fields, and clusters can add CustomResourceDefinitions for tools such as certificate managers, policy engines, and database operators. Kubernetes gives you a better approach: query the OpenAPI schema through kubectl explain. This turns the cluster itself into the version-matched reference for the fields it accepts. This lesson uses the full command name in its examples.
Traverse from a kind to the field you want to inspect. For a Pod, ask for pod.spec to see its field descriptions and type hints before choosing a nested path. The hints describe the expected shape: <string> is a string scalar, a named type such as <Probe> is an object, a [] prefix denotes a list, and <map[string]string> is a mapping of string keys to string values. Translate those shapes into YAML scalars, mappings and sequences; inspect the actual output for the field and cluster version rather than memorizing a generic placeholder type.
# General syntax: kubectl explain <kind>.<field>.<field>kubectl explain pod.specUse --recursive to request a field outline. Output can vary by resource and version, so query an exact path for details rather than assuming a complete tree. This is especially useful for CRDs that publish an OpenAPI schema, because the reference matching the target cluster may differ from an old public example.
kubectl explain pod.spec --recursiveA liveness probe is a nested example because it has several options, and only some combinations make sense. You can ask for the probe field first to see the available probe mechanisms, then drill into the HTTP action to inspect the path and port fields. That workflow scales from built-in resources to CRDs as long as the CRD publishes a usable OpenAPI schema.
kubectl explain pod.spec.containers.livenessProbeThe following is an abridged legacy-format illustration; the exact header and wording can differ from current kubectl output.
KIND: PodVERSION: v1
RESOURCE: livenessProbe <Probe>
DESCRIPTION: Periodic probe of container liveness.
FIELDS: exec <ExecAction> Exec specifies the action to take.
httpGet <HTTPGetAction> HTTPGet specifies the http request to perform....You can continue drilling down even further to see the exact parameters required for configuring an HTTP-based liveness probe, checking for things like the expected path and port specifications:
kubectl explain pod.spec.containers.livenessProbe.httpGetThe --recursive flag gives a structural outline without requiring a separate lookup for every immediate field, but it is not a substitute for targeted lookup. For a Deployment’s container list, query deployment.spec.template.spec.containers directly. The path reminds you that the Pod template is nested under the Deployment spec, while container fields belong under the template’s Pod spec.
kubectl explain deployment.spec.template.spec.containersBefore running this, what output do you expect if you ask for kubectl explain pod.spec.nodeSelector? You should expect a field description and a type that behaves like a mapping from string keys to string values. That means the YAML shape is not a list of selector objects; it is a mapping such as disktype: ssd, where each key and value correspond to node labels.
kubectl explain pod.spec.nodeSelectorThis schema-first workflow is useful in air-gapped environments when the target cluster publishes the relevant schema, including a CRD’s schema. A generic example may describe a different version from the one installed in the cluster. Admission policies and runtime behavior need separate checks, even after a field appears in the schema. Ask the cluster precise questions, then translate the returned types into YAML shapes and use an appropriate validation step before deployment.
4. Common YAML Patterns in Kubernetes
Section titled “4. Common YAML Patterns in Kubernetes”The same small set of YAML structures appears repeatedly in real manifests, but the consequences differ by field. A list under containers describes container definitions. A Service selector mapping identifies matching pods. A two-part relationship between volumes and volumeMounts affects whether a pod can start. Once you train yourself to identify those shapes, error messages become clues instead of noise.
Environment variables illustrate a sequence of mappings. The env field under a container does not accept a single mapping of names to values. It accepts a list, and each list item is a mapping with a name field plus either a direct value or a valueFrom reference. This design lets each environment variable carry additional structure, such as references to ConfigMaps, Secrets, fields, or resource values.
apiVersion: v1kind: Podmetadata: name: env-demospec: containers: - name: my-app image: nginx:alpine env: # The 'env' field takes a Sequence (List) - name: DATABASE_URL # First item in the list, direct value value: "postgres://db:5432" - name: LOG_LEVEL # Second item in the list value: "debug" - name: API_KEY # Third item, value injected from a Secret valueFrom: secretKeyRef: name: app-secrets key: api-keyEvery environment variable starts with a hyphen at the same indentation level. Removing one can merge keys into the preceding item or create another unintended shape, even if the file still looks close to correct. The resulting validation error depends on the data produced; a duplicate key and a list-versus-mapping error are not interchangeable diagnoses. Inspect that shape and use kubectl explain pod.spec.containers.env rather than guessing.
Volumes demonstrate a different source of mistakes because the configuration is split across two parts of the pod. The pod-level spec.volumes sequence declares volume sources, such as ConfigMaps, Secrets, empty directories, projected volumes, or persistent volume claims. Each container-level volumeMounts sequence decides where a named volume appears inside that container’s filesystem. The link between those blocks is the volume name, so the names must match exactly.
apiVersion: v1kind: Podmetadata: name: volume-demospec: containers: - name: app-container image: busybox command: ["sleep", "3600"] volumeMounts: # Where does the container see the volume? - name: config-store # Must match the volume name below exactly! mountPath: /etc/config readOnly: true volumes: # What is the actual volume backing this? - name: config-store # The identifier configMap: # The volume type (populates files from a ConfigMap) name: my-app-configOne pod can define several volumes and containers can mount different subsets at different paths. This split allows one source to be presented differently to different containers, but it makes the shared name worth checking carefully. A mount name with no matching volume is valid YAML but fails API validation; server dry run can catch it. Compare both name fields before deployment. For startup problems after acceptance, inspect the affected Pod and its related events with kubectl describe pod <name>.
Labels and selectors are mappings that connect resources without hard-coding pod names. For a selector-based Service, Kubernetes uses the selector to identify matching pods and manage backend endpoint information. That indirection lets Kubernetes replace pods during rollouts while the Service remains stable. Labels must match, but readiness and networking also affect whether traffic succeeds. A one-character label mismatch can leave a Service without matching endpoints.
# A Service looking for specific podsapiVersion: v1kind: Servicemetadata: name: frontend-svcspec: selector: # Select Pods... app: frontend # ...that have this exact label tier: web # ...AND this exact label. ports: - port: 80The selector above is an AND relationship across mapping keys. A pod must have both app: frontend and tier: web to match this selector; matching alone does not prove it can receive traffic. This is why Deployment pod-template labels and Service selectors deserve careful review together. If the Deployment creates pods with tier: frontend while the Service selects tier: web, both resources can be valid and still fail as a system because the intended relationship is broken.
Which approach would you choose here and why: hard-code pod names into a client configuration file, or use a Service selector that matches stable labels? Use selectors for normal Kubernetes networking because pods are disposable and labels are the stable contract. Hard-coded pod names turn routine rollouts into configuration churn, while selectors let controllers replace pods without forcing clients to learn new identities.
5. Multi-Resource Files and CI/CD
Section titled “5. Multi-Resource Files and CI/CD”An application can combine several Kubernetes objects. Even a small web service may need a ConfigMap for configuration, a Deployment for compute, a Service for stable networking, an Ingress for external routing, and perhaps a ServiceAccount or Secret. Keeping each object in a separate file can be clear for large repositories, but for a compact teaching example or a small application unit, a multi-document YAML file keeps related resources together while still preserving separate Kubernetes objects.
YAML uses --- as a document-start marker. In these multi-document examples, three hyphens on a line by themselves start a new document and separate it from the preceding one. kubectl apply -f combined.yaml reads that stream, splits it into individual objects, and submits them in order. Each object still has its own apiVersion, kind, metadata, and object-specific state. The separator does not merge objects; it lets one file carry several independent objects.
apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: color: "blue"---apiVersion: apps/v1kind: Deploymentmetadata: name: my-appspec: replicas: 2 # ... deployment details ...---apiVersion: v1kind: Servicemetadata: name: my-app-svcspec: # ... service details ...kubectl processes documents in file order, while controllers reconcile asynchronously after objects exist. A Deployment can be accepted before its referenced ConfigMap exists; a Pod cannot start while a required ConfigMap reference is missing, as the ConfigMap restrictions explain. This distinction explains why acceptance of the first document is not proof that its dependent workload is ready. Ordering dependencies first reduces avoidable startup errors and makes the first rollout easier to observe.
Put foundational dependencies before workloads where practical. Multi-document files package related objects; they do not replace dependency design or make reconciliation synchronous.
Pause and predict: does document order matter when you run kubectl apply -f combined.yaml?
Check your prediction
The client processes documents in order, but the cluster reconciles them over time. A Pod cannot start while a required ConfigMap is missing. Order dependencies first to reduce avoidable startup errors and make first-apply behavior easier to reason about.
Write whether order matters, and to whom, before you continue. The next paragraph treats the file as one validation unit. It does not say whether the client waits for reconciliation.
CI/CD validation should treat multi-resource files as a single deployment unit but inspect each object separately. A syntax error can stop processing of the remaining stream depending on the tool, so check each document. A schema error in one resource can fail the apply even if other resources are valid. A selector mismatch can pass validation entirely because it is a semantic relationship between objects rather than a local schema violation. Combine YAML parsing, server-side dry runs, and appropriate policy or integration checks to examine different failure layers.
6. Validating YAML and Real Debugging
Section titled “6. Validating YAML and Real Debugging”Debugging manifests becomes manageable when you distinguish failure types. Can YAML syntax be parsed into data? Does the data match the declared Kubernetes resource schema? Can discovery, authorization, and admission process the request in the target cluster? After acceptance, do controllers and workloads reach the desired state? These checks involve distinct stages; use the actual response to identify where a request failed.
Client-side dry run is a useful first pass while editing. It may contact the API server for discovery or schema information, but it does not send the object through server-side dry-run admission. Client dry run may accept invalid fields, so success is not reliable proof of schema correctness; use server dry run for the exercise below. Neither dry run proves runtime behavior or dependency availability.
kubectl apply -f my-pod.yaml --dry-run=clientServer-side dry run asks the actual API server to process the request through authentication, authorization, schema validation, defaulting, and admission control, but it stops before persisting the object. That makes it the better preflight for shared clusters, CRDs, and policy-heavy environments. If your CI system has cluster access, server-side dry run gives you confidence that the real control plane can accept the manifest under current conditions.
kubectl apply -f my-pod.yaml --dry-run=serverThe diff command asks what would change compared with live state. This matters because an object can pass validation while still changing a relationship the operator meant to keep. An apps/v1 Deployment selector is immutable after creation, while a Service selector change can remove endpoints. A server dry run checks the server’s acceptance under current conditions; a diff helps you assess whether the proposed change matches the intended operational outcome.
kubectl diff -f my-updated-deployment.yamlStart with the exact error and identify the layer. For YAML-to-JSON parsing errors, inspect nearby indentation, colons, tabs and sequence markers. For an invalid field or type, inspect the expected path with kubectl explain. With a Kubernetes 1.27+ server, client dry run can succeed while ordinary schema errors appear during server dry run; also investigate namespace, CRD, RBAC and admission causes. Keep the error and the command that produced it together, because a validation response and a workload event describe different stages of the request lifecycle.
Treat each verifier result as evidence about where the manifest failed, not as a personal judgment about the author. A parser error says the text did not become a data tree, so editing the apiVersion will not help until the indentation or scalar syntax is repaired. A schema error says the data tree exists but does not match the object contract, so adding more document separators will not fix a misplaced image field. An admission rejection can identify a cluster policy constraint, such as a required ownership label or a resource quota. Diagnose the specific request stage from the response rather than inferring complete schema correctness from one message.
error: error parsing deployment.yaml: error converting YAML to JSON: yaml: line 15: mapping values are not allowed in this contextThis illustrative message describes a YAML parsing failure before Kubernetes validation. Use the line as a clue and inspect surrounding structure: indentation, sequence markers and unquoted colons can change what the parser expects.
The Deployment "my-app" is invalid: spec.replicas: Invalid value: "3": spec.replicas must be an integerThis illustrative message describes a schema type mismatch; actual 1.35 diagnostics differ. YAML accepted "3" as a string, but spec.replicas requires an integer. Use replicas: 3 without quotes. The repair changes the value’s type to the one the schema expects; it does not require disabling validation or changing the Deployment’s API group.
error: unable to recognize "pod.yaml": no matches for kind "Pod" in version "apps/v1"This illustrative message points to the root contract. Pods use v1; apps/v1 includes controllers such as Deployments. Kubectl cannot map an unmatched group/version/kind through discovery before submitting the object; discovery itself can contact the server.
Illustrative diagnostic: duplicate mapping key "port"This message is illustrative. YAML mappings require unique keys; non-strict conversion can silently retain one duplicate in an undefined order. Strict validation can reject duplicates. Use a sequence when multiple ports are intended or remove the duplicate key.
error: error validating "deployment.yaml": error validating data: ValidationError(Deployment.spec.template.spec): unknown field "image" in io.k8s.api.core.v1.PodSpec;This illustrative legacy-format message identifies an unknown field; actual strict 1.35 output differs. Here image belongs inside a container under spec.template.spec.containers[], not directly under the pod spec. Follow the reported path and inspect the schema with kubectl explain.
Exercise scenario: a platform team adds a new podLabels field copied from a Helm chart values file directly under Deployment.spec in a rendered manifest. The field makes sense in the chart input, but podLabels is not a Deployment.spec field; Pod template labels belong under spec.template.metadata.labels. Client-side checks on one developer laptop miss it because the local script skips validation for generated files, while server-side dry run in CI rejects it before production. The right repair is to fix the chart template or values mapping instead of weakening validation, because the problem is a boundary mistake between a templating interface and the Kubernetes API.
Patterns & Anti-Patterns
Section titled “Patterns & Anti-Patterns”Strong Kubernetes YAML practice is less about memorizing snippets and more about creating reviewable patterns. A good pattern makes the intended data shape obvious, gives controllers stable relationships to reconcile, and lets validation fail early when the file does not match the schema. A bad pattern may still produce valid YAML, but it hides meaning, depends on accidental ordering, or lets a semantic mismatch escape into runtime behavior.
| Pattern | When to Use It | Why It Works | Scaling Considerations |
|---|---|---|---|
| Schema-first authoring | Any time you add an unfamiliar field or nested structure | kubectl explain tells you the expected Kubernetes type before you write YAML | Works for built-ins and well-defined CRDs; supplement with vendor docs when CRD schemas are sparse |
| Dependency-first multi-document files | Small app bundles with ConfigMaps, Secrets, workloads, and Services | Successfully creating prerequisites first can reduce missing-dependency startup errors | Larger systems may move ordering into GitOps waves or separate Kustomize bases |
| Stable label contracts | Services, Deployments, and NetworkPolicies | Labels provide durable relationships while pods remain disposable | Define label conventions centrally so teams do not invent incompatible keys |
| Server-side dry run in CI | Shared clusters, CRDs, namespaces, RBAC, and admission policies | The real API server validates the request without persisting it | Requires safe CI credentials and representative target clusters |
| Anti-Pattern | What Goes Wrong | Why Teams Fall Into It | Better Alternative |
|---|---|---|---|
| Guessing list versus mapping shape | The file is valid YAML but fails schema validation or creates the wrong object shape | Examples look visually similar, especially around containers, env, and ports | Read the schema type: a list needs sequence items |
| Copying chart values into manifests | Tool-specific input fields absent from the target API schema can fail strict validation | The chart input and rendered output both use YAML, so the boundary feels blurry | Render the chart, inspect the output, and validate the actual Kubernetes manifest |
| Quoting every scalar defensively | Integers and booleans become strings where the schema requires native types | Teams try to avoid YAML type surprises by treating everything as text | Quote ambiguous strings, but leave numeric fields unquoted when the schema expects numbers |
| Treating client dry run as final proof | Client dry run does not reproduce every server validation or admission check; some constraints surface during server processing | Client validation gives useful early feedback | Use client dry run for editing and server-side dry run before merge or release |
The most reliable pattern is to keep the intended object relationships near each other during review. If a Service selects app: web, reviewers should be able to see the pod template labels that satisfy that selector. If a container mounts config-store, reviewers should be able to see the pod-level volume named config-store. If an environment variable references app-config, reviewers should be able to see whether that ConfigMap is created by the same release unit or by a documented external dependency.
Decision Framework
Section titled “Decision Framework”Choosing the right YAML and validation approach depends on the risk of the change, the cluster features involved, and the feedback speed you need. A local edit loop should be fast because you are shaping the document. A release gate should be authoritative because it represents a change the cluster may actually run. A production update should be inspectable because accepted changes can still be operationally dangerous.
Start with a manifest change | vIs the field path unfamiliar? | +-- yes --> Run kubectl explain for the exact path, then edit the YAML shape | +-- no ----+ | vHave you checked the file's structure? | +-- no --> Use client dry run for early feedback; verify types with server dry run | +-- yes ---+ | vDoes the target cluster have CRDs, RBAC, or admission policy involved? | +-- yes --> Run kubectl apply --dry-run=server against that cluster | +-- no ----+ | vAre you updating existing live resources? | +-- yes --> Run kubectl diff -f <file> and review the patch | +-- no ---> Apply through the normal release workflowUse client-side dry run when you are still editing and want immediate feedback on obvious syntax or schema problems. Use server-side dry run when the live cluster’s view matters, which includes CRDs, namespaces, RBAC, admission controllers, defaulting, and version-specific validation. Use diff when the object already exists and the important question is not “is this valid?” but “what exactly will change?” These checks answer different questions; choose those needed for the change.
| Situation | Preferred Tool | Reason |
|---|---|---|
You cannot remember where readOnly belongs for a volume mount | kubectl explain pod.spec.containers.volumeMounts | The schema shows the exact nested field path and expected type |
| You are editing a local Pod example and want fast feedback | kubectl apply --dry-run=client -f pod.yaml | Client checks give early feedback, may contact the API, and may accept invalid fields |
| You are validating an operator CRD before merge | kubectl apply --dry-run=server -f resource.yaml | The API server validates the installed CRD version and admission policy |
| You are changing a live Service selector | kubectl diff -f service.yaml | The diff exposes relationship changes before they are applied |
The framework also tells you when YAML is not the real problem. If server-side dry run accepts a Service but traffic still fails, inspect endpoints and labels rather than rewriting indentation. If a ConfigMap is valid but the application ignores it, inspect how the pod consumes it through environment variables or mounted files. YAML is the delivery format for desired state, but runtime debugging still requires following the controller and workload behavior after the API accepts the object.
Did You Know?
Section titled “Did You Know?”- YAML version differences: YAML 1.2’s core schema treats
yesandnoas strings, but Kubernetes 1.35’s vendored YAML-to-JSON library documents YAML 1.1-style boolean conversion. Quote ambiguous strings and check the parser used by your tool. - ConfigMap data is bounded: Kubernetes documents a 1 MiB limit for ConfigMap data. Consider another configuration delivery mechanism when data approaches that limit.
- JSON is valid YAML: YAML is designed so JSON documents are also valid YAML documents.
kubectlcan apply JSON files directly, which is useful for generated payloads and API integrations where human editing is not the main goal. - The API server cares about structure, not formatting taste: Two manifests can look similar in a review while producing different data trees. A missing sequence hyphen under
containerschanges the data type, and the API server validates the data tree after parsing, not your visual intention.
Common Mistakes
Section titled “Common Mistakes”| Mistake | Why It Happens | How to Fix It |
|---|---|---|
| Using tabs for indentation | Copying from chat tools, browsers, or editors that insert tabs makes YAML invalid before Kubernetes sees it. | Configure the editor to insert two spaces for YAML files and show whitespace during review. |
Pairing the wrong apiVersion with a kind | Engineers guess from nearby examples, such as using v1 for a Deployment because Pods use v1. | Run kubectl api-resources or kubectl explain <kind> and verify the API group before writing the manifest. |
| Missing hyphens for sequences | Fields like containers, env, ports, and volumeMounts look like nested mappings until you inspect their schema. | If kubectl explain shows a list type, write sequence items at the correct indentation. |
| Quoting values with the wrong type | Teams quote every value to avoid YAML surprises, then fields like replicas or port become strings. | Quote ambiguous strings, but leave numeric schema fields unquoted when Kubernetes expects integers. |
Forgetting --- between resources | Multiple resources are pasted into one file and the parser treats them as one broken or overwritten document. | Place --- on a line by itself between complete Kubernetes objects in a multi-document file. |
| Mismatching Service selectors and pod labels | Each resource validates locally, but the relationship between them is semantic and easy to miss. | Review Service selectors beside Deployment pod-template labels and confirm endpoints after apply. |
Using > for structured multi-line data | Folded scalars are readable, but they replace ordinary line breaks with spaces. | Use | for scripts, certificates, kubeconfig fragments, and any data where newlines are syntax. |
| Treating client dry run as production proof | Client validation is fast, so teams promote it to the only gate even when clusters use CRDs and policies. | Keep client dry run for authoring, then run server-side dry run against the target cluster before release. |
1. Scenario: A colleague asks you to review a pull request where a Kubernetes Secret containing a private TLS certificate fails to parse in the ingress controller. You notice the certificate data is defined with the `>` YAML operator. Why is this causing the failure, and how do you fix it?
Answer: The folded block scalar > converts ordinary line breaks into spaces, altering the PEM text even though the YAML document can still parse successfully. In this scenario the consumer rejects that altered text; other parsers may behave differently. Use the literal block scalar | to preserve the line structure, and compare the decoded value with the intended certificate. This answer tests the outcome about constructing manifests with the correct multi-line string form and diagnosing failures where valid YAML carries altered application data.
2. Scenario: During a production hotfix, an engineer runs `kubectl apply -f hotfix.yaml` and receives `error converting YAML to JSON: yaml: line 22: did not find expected key`. Line 22 contains `image: nginx:alpine`, which looks harmless. What should they inspect first?
Answer: Inspect indentation and sequence structure around containers, including the surrounding text, before deciding which edit is needed. A misplaced sequence marker or name field can change the resulting structure.
3. Scenario: You are in an air-gapped cluster and need to mount a PersistentVolumeClaim, but you cannot remember whether `readOnly` belongs under `volumes` or `volumeMounts`. How do you find the correct field path without web access?
Answer: Compare kubectl explain pod.spec.volumes.persistentVolumeClaim with kubectl explain pod.spec.containers.volumeMounts. A PVC volume source and a container mount both have readOnly; the source setting can force mounts read-only, while the mount setting applies to that mount. Read the descriptions and types for your target version.
4. Scenario: A Custom Resource manifest is rejected immediately, and the error says the object cannot be recognized. The YAML syntax is valid and indentation is clean. Which root-level Kubernetes contract should you verify?
Answer: Verify apiVersion and kind, then metadata.name and the expected body. Kubectl uses discovery to map a group/version/kind before submitting an object. For a custom resource, confirm the version is served by the installed CRD; discovery may itself contact the API server.
5. Scenario: A 500-line application bundle passes `kubectl apply --dry-run=client -f app.yaml`, but the real apply is rejected by an admission policy for a required label. Why did client-side validation miss it, and what should the pipeline do?
Answer: Client dry run may contact the API server for discovery or schema information, but it does not send the object through server-side dry-run admission, so it misses the required-label admission policy. Run kubectl apply --dry-run=server -f app.yaml against a representative cluster before applying the change. That checks the request against the server’s validation and admission path; it does not establish runtime behavior or prove dependent objects will be available.
6. Scenario: A Service is valid and a Deployment is valid, but the Service has no endpoints after deployment. The Service selector is `app: frontend` and `tier: web`, while the pod template labels are `app: frontend` and `tier: ui`. What is wrong?
Answer: The YAML and schemas can both be valid while the semantic relationship is broken. A Service selector is an AND match across all selector keys, so pods must have both app: frontend and tier: web to become endpoints. Since the pods have tier: ui, the Service selects nothing. Fix either the Service selector or the pod template labels so the intended label contract matches, then inspect membership for a Service named frontend-svc in the current namespace with kubectl get endpointslices -l kubernetes.io/service-name=frontend-svc. The legacy Endpoints API has been deprecated since Kubernetes 1.33.
7. Scenario: A release file contains a ConfigMap, a Deployment that consumes it as an environment variable, and a Service. A teammate wants the Deployment first because it is the "main" resource. How would you evaluate that choice?
Answer: Dependency-first ordering can reduce startup errors and make diagnostics easier. A Pod cannot start while a required ConfigMap is absent; optional references behave differently. Put the ConfigMap before the Deployment, then put the Service where it best fits the review flow. This tests the design outcome around multi-resource manifests and the tradeoff between asynchronous reconciliation and a clean first apply.
Hands-On Exercise
Section titled “Hands-On Exercise”In this synthetic exercise, you will build a small multi-resource application manifest, intentionally encounter structural failures, and use server dry runs to repair them. Server dry run sends requests through validation and admission without persisting the objects. Use an independently confirmed dedicated disposable Kubernetes 1.35+ lab context and an existing namespace in that lab. The conceptual examples earlier in this module are separate from this dry-run exercise.
Set KUBEDOJO_LAB_CONTEXT and KUBEDOJO_LAB_NAMESPACE to the confirmed context and existing namespace before setup; the literal context name default is refused (a namespace named default is allowed). Use one fresh Bash terminal. The guard cannot prove the cluster is disposable, and it does not change kubeconfig preferences. Setup uses mktemp -d to create and enter a fresh scratch directory so dojo-app.yaml cannot overwrite an existing file; retain it for inspection and remove it manually when no longer needed. See the FreeBSD and GNU manuals.
YAML_READY=no YAML_NEW=noreadonly YAML_CONTEXT="${KUBEDOJO_LAB_CONTEXT:-}" YAML_NS="${KUBEDOJO_LAB_NAMESPACE:-}" && YAML_NEW=yesyaml_check() { [ "$YAML_READY" = yes ] || { echo 'Setup incomplete; stop' >&2; return 1; } command kubectl --context "$YAML_CONTEXT" --namespace "$YAML_NS" apply --dry-run=server -f dojo-app.yaml}if [ "$YAML_NEW" = yes ] && [ -n "$YAML_CONTEXT" ] && [ "$YAML_CONTEXT" != default ] && [ -n "$YAML_NS" ] && YAML_CURRENT="$(command kubectl config current-context)" && [ "$YAML_CURRENT" = "$YAML_CONTEXT" ] && YAML_DIR="$(mktemp -d "${TMPDIR:-/tmp}/yaml-lab.XXXXXXXX")" && cd "$YAML_DIR"; then YAML_READY=yes printf 'Exercise context/namespace/directory: %s / %s / %s\n' "$YAML_CONTEXT" "$YAML_NS" "$YAML_DIR"fi[ "$YAML_READY" = yes ] || echo 'Setup failed; stop and inspect the error before continuing' >&2Continue only after setup succeeds. Create dojo-app.yaml in the printed directory. The first version is intentionally broken in several ways: the API version is wrong for a Deployment, a numeric field is quoted as a string, and the container list is missing its sequence structure.
Task 1: The Broken Foundation
Section titled “Task 1: The Broken Foundation”Create dojo-app.yaml with this payload, then run yaml_check and read the first error carefully.
apiVersion: v1kind: Deploymentmetadata: name: web-appspec: replicas: "2" selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: name: nginx image: nginx:1.27Solution & Diagnosis 1
You may see an error similar to no matches for kind "Deployment" in version "v1"; validation order and diagnostics can vary. Change apiVersion: v1 to apiVersion: apps/v1 because Deployments belong to the apps API group, not the core group. This repair addresses the Kubernetes root contract before you debug deeper structure.
Task 2: The Type and Structure Failures
Section titled “Task 2: The Type and Structure Failures”Run yaml_check again. Fix the next errors one at a time instead of trying to rewrite the whole file from memory. Review the schema examples above for the integer field and sequence shape.
Solution & Diagnosis 2
First, change replicas: "2" to replicas: 2 because the Deployment schema expects an integer, not a string. Second, repair the container list because containers expects a sequence of container objects.
containers: name: nginxshould become:
containers: - name: nginx image: nginx:1.27The original YAML can parse: name and image become siblings of containers. Strict server field validation rejects those unknown PodSpec fields; adding the hyphen puts them inside the container sequence. Diagnostic wording can vary.
Task 3: Adding a Service Safely
Section titled “Task 3: Adding a Service Safely”After the Deployment validates, append a Service object to the bottom of the same file. The Service should expose port 80 and route to pods with app: web. Use the YAML document separator so the Service is a separate Kubernetes object rather than a malformed continuation of the Deployment.
Solution 3
Add --- at the end of the Deployment document, then append the Service definition:
---apiVersion: v1kind: Servicemetadata: name: web-app-svcspec: selector: app: web ports: - port: 80 targetPort: 80Task 4: Adding a ConfigMap Dependency
Section titled “Task 4: Adding a ConfigMap Dependency”Add a third resource at the very top of the file, before the Deployment. The ConfigMap should be named app-config and should contain one key, welcome-message, with the value "Hello KubeDojo!". Keep a separator between the ConfigMap and the Deployment so each object remains independent.
Solution 4
Add this to the very top of dojo-app.yaml and separate it from the Deployment with ---.
apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: welcome-message: "Hello KubeDojo!"---Task 5: Connecting the Pieces
Section titled “Task 5: Connecting the Pieces”Modify the Deployment so the nginx container reads the ConfigMap key as an environment variable named GREETING. Then run the server dry run on the complete file.
yaml_checkSolution 5
Your final, valid dojo-app.yaml should look like this:
apiVersion: v1kind: ConfigMapmetadata: name: app-configdata: welcome-message: "Hello KubeDojo!"---apiVersion: apps/v1kind: Deploymentmetadata: name: web-appspec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: nginx image: nginx:1.27 env: - name: GREETING valueFrom: configMapKeyRef: name: app-config key: welcome-message---apiVersion: v1kind: Servicemetadata: name: web-app-svcspec: selector: app: web ports: - port: 80 targetPort: 80When you run yaml_check successfully, output should identify all three resources as server dry runs. The exact wording can vary:
configmap/app-config created (server dry run)deployment.apps/web-app created (server dry run)service/web-app-svc created (server dry run)This checks the requests through the server validation and admission path; it does not prove scheduling, image availability, Service reachability, or application behavior. Server dry runs do not persist the ConfigMap for a dependent object, so they cannot establish that the running bundle will find its dependency. Inspect references and selectors separately; this exercise never persists the objects.
Task 6: Design and Check a Label Contract
Section titled “Task 6: Design and Check a Label Contract”Choose a valid label value such as qa and add it as tier to the Deployment’s Pod template labels; leave the Deployment selector unchanged. Write down your prediction of what happens if the Service selects a different value. In your scratch file, add tier with a different valid value such as preview to the Service’s spec.selector, then run yaml_check and compare the mappings: server dry run can succeed even when no Pods match the Service selector, so its success does not prove endpoint membership. Correct the Service selector to match your chosen value and run yaml_check again. Record the mismatch, both outcomes, and why the matched mappings matter. Keep using server dry run; do not apply the bundle.
Hint 1
Which two mappings connect a Service to Pods?Hint 2
Compare every Service selector key and value with the Pod template labels; do not change the Deployment selector.Hint 3
After trying a mismatch, align the Service'stier with the template label, then run yaml_check again.After your attempt: one possible approach
A template labeltier: web and Service selector tier: api do not match. Change the Service value to web, inspect both mappings, and repeat the dry run. Other label values work if the mappings agree.Card A: The sequence count is off. A reviewer counts every hyphen in the users block, including the ones under permissions, and reports five users.
Check your prediction
Failure layer: indentation, not the hyphen character. Next action: count hyphens only at the users item indent, then read permissions as a nested sequence of strings.
Card B: The certificate parses and still fails. A Secret embeds a .pem with >. kubectl apply succeeds. The process later rejects the key.
Check your prediction
Failure layer: the folded scalar turned newlines into spaces. Next action: switch that block to | and compare the decoded text before you rotate anything else.
Card C: The merge looks nested. After <<: *common_labels, someone expects metadata.base_labels.app. The JSON shows sibling keys instead.
Check your prediction
With a parser that supports the YAML 1.1 merge extension, the alias contributes keys to the parent mapping. Check your parser’s output rather than assuming every YAML implementation supports it.
Card D: The ConfigMap uses spec. The file has apiVersion, kind, and metadata. The keys sit under spec.data. The API rejects the object.
Check your prediction
Failure layer: a data object was given a workload body. Next action: move the keys to data and keep apiVersion, kind, and metadata.
Card E: Apply is treated as one transaction. combined.yaml lists the Deployment before its required ConfigMap. A Pod cannot start while the required reference is missing. The pipeline calls that a broken apply.
Check your prediction
Failure layer: the client sent documents in order, and the controllers reconciled later. Next action: put the ConfigMap first, and do not expect kubectl apply to wait until every dependency is ready.
Exercise Success Checklist
Section titled “Exercise Success Checklist”- You triggered an API group error and fixed it by changing the Deployment from
v1toapps/v1. - You identified a quoted integer problem and changed
replicas: "2"toreplicas: 2. - You repaired a sequence indentation problem by adding the missing container hyphen.
- You appended a Service as a separate YAML document using
---. - You prepended a ConfigMap dependency and referenced it from the Deployment environment.
- You ran the server dry run and identified its limits for the ConfigMap, Deployment, and Service.
- You chose a
tier, diagnosed a selector mismatch, aligned the mappings and recorded why dry run alone cannot prove endpoint membership.
Sources
Section titled “Sources”- Kubernetes API overview
- Kubernetes objects
- Kubernetes v1.35 Deployments: label selector updates
- Kubernetes object management
- Kubernetes labels and selectors
- Kubernetes annotations
- Kubernetes ConfigMaps
- Kubernetes Secret API reference
- Kubernetes Deployment API reference, pinned source
- Kubernetes NetworkPolicies
- kubectl describe reference
- RFC 8259: JSON
- Kubernetes v1.35.0 tag reference and annotated tag object
- Configure Pods with a ConfigMap: restrictions
- RFC 7468: Textual Encodings of PKIX, PKCS, and CMS Structures
- Kubernetes Secrets
- Kubernetes volumes
- Kubernetes v1.35.0 core volume types
- Kubernetes v1.35 Services and EndpointSlices
- kubectl explain reference
- kubectl v1.35 explain implementation and recursive output template
- Kubernetes v1.35 kubectl apply reference
- Kubernetes v1.35 API dry-run and field validation
- Kubernetes v1.35 CRD versions
- kubectl v1.35.0 apply implementation
- kubectl diff reference
- YAML 1.2.2 specification
- YAML 1.1 specification, merge working draft, Kubernetes v1.35.0 vendored YAML converter, and vendored YAML v2 decoder
- FreeBSD mktemp, GNU mktemp
Next Module
Section titled “Next Module”You have now practiced YAML as the language of Kubernetes desired state: structure first, schema second, validation before mutation. Continue to Philosophy and Design to see why Kubernetes is built around declarative APIs, asynchronous reconciliation, and controllers that continuously move actual state toward the state you declare.