Kubernetes YAML Validator
Comprehensive toolkit for validating, linting, testing Kubernetes YAML resources. Use this skill when validating Kubernetes manifests, debugging YAML syntax errors, performing dry-run tests on clusters, working with Custom Resource Definitions (CRDs) that require documentation lookup.
npx skills add github:pantheon-org/tekhne --skill infrastructure--k8s--yaml-validatorMindset
Mental Model: Validation is a layered funnel—syntax → schema → cluster constraints → runtime behavior. Each layer catches different classes of errors, and a pass at one layer must never be read as a pass at the next: yamllint clean says nothing about schema compliance, and kubeconform clean says nothing about whether an admission webhook will reject the resource. You must always run every applicable layer, never stop at the first one that returns clean. The classic pitfall this catches: a manifest that is syntactically perfect and schema-valid but still gets rejected by a PodSecurity admission webhook — a gotcha that only the cluster-constraints layer can surface.
Decision Framework:
- Syntax first: Fix YAML structure before schema issues (broken YAML can’t be validated)
- Schema second: Verify API compliance before cluster-specific checks
- Cluster third: Test against real constraints (RBAC, quotas, admission webhooks)
- Runtime last: Consider how the resource behaves in production
When to use this skill:
- Before applying any YAML to a cluster (development, staging, production)
- When debugging mysterious kubectl apply failures
- During CI/CD pipeline execution (catch errors early)
- When working with unfamiliar CRDs (validation guides learning)
- After generating YAML with k8s-yaml-generator
When NOT to use this skill:
- The manifest has already passed server-side dry-run against the exact target cluster and namespace in this same session, and nothing has changed since — re-running the full funnel adds no new information.
- The task is generating a new resource rather than checking an existing one — use
k8s-yaml-generatorand let its own validation step call into this skill. - Only a single, well-understood field is in question (e.g. confirming a typo) — a direct
kubectl explainlookup is faster and does not require the full workflow.
Validation philosophy: Report all issues, prioritize by severity, suggest fixes but never apply them automatically — this is a hard constraint, not a stylistic preference, and it must never be relaxed even when a fix is obvious.
Overview
This skill provides a comprehensive validation workflow for Kubernetes YAML resources, combining syntax linting, schema validation, cluster dry-run testing, and intelligent CRD documentation lookup. Validate any Kubernetes manifest with confidence before applying it to the cluster.
IMPORTANT — REPORT-ONLY: Do NOT modify files, use the Edit tool, or offer to apply fixes. Generate a comprehensive validation report with suggested fixes shown as before/after code blocks, then let the user decide what to do next.
Validation Workflow
Follow this sequential validation workflow. Each stage catches different types of issues:
Stage 0: Pre-Validation Setup (Resource Count Check)
Before running any validation tools, check the file complexity:
- Count the number of resources by counting
---document separators or parsing the file - If the file contains 3 or more resources, immediately load
references/validation_workflow.md:Read references/validation_workflow.md - Note the resource count for the validation report summary
Stage 1: Tool Check
bash scripts/setup_tools.sh
Required tools: yamllint, kubeconform, kubectl (optional). If tools are missing, display installation instructions from script output and document missing tools in the validation report.
Stage 2: YAML Syntax Validation
yamllint -c assets/.yamllint <file.yaml>
Report all syntax issues with file:line references. Show suggested before/after code blocks. Continue to the next stage to collect all issues before reporting.
Stage 3: CRD Detection and Documentation Lookup
bash scripts/detect_crd_wrapper.sh <file.yaml>
The wrapper script automatically handles Python dependencies via a temporary virtual environment if PyYAML is not available.
Resilient Parsing: The script parses valid documents and reports errors for invalid ones — continuing processing rather than aborting. This matches kubeconform’s behavior of validating 2/3 resources when 1/3 has syntax errors.
Script outputs JSON with resource information and parse status:
{
"resources": [
{
"kind": "Certificate",
"apiVersion": "cert-manager.io/v1",
"group": "cert-manager.io",
"version": "v1",
"isCRD": true,
"name": "example-cert"
}
],
"parseErrors": [
{
"document": 1,
"start_line": 2,
"error_line": 6,
"error": "mapping values are not allowed in this context"
}
],
"summary": {
"totalDocuments": 3,
"parsedSuccessfully": 2,
"parseErrors": 1,
"crdsDetected": 1
}
}
For each detected CRD:
-
Look up the CRD documentation:
kubectl explain <kind>.spec # if the CRD is installed in a reachable cluster Search: "<project> <kind> <version> spec fields" Example: "cert-manager Certificate v1 spec fields" Example: "istio VirtualService v1beta1 specification" -
Fallback to WebSearch if documentation is insufficient:
"<kind>" "<group>" kubernetes CRD "<version>" documentation spec -
Extract required
specfields, field types, validation rules, and version-specific changes.
Secondary CRD Detection: If detect_crd_wrapper.sh fails (e.g., all documents have syntax errors) but kubeconform validates a CRD resource, parse kubeconform output to identify those CRDs and perform documentation lookups.
Stage 4: Schema Validation
kubeconform \
-schema-location default \
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
-strict \
-ignore-missing-schemas \
-summary \
-verbose \
<file.yaml>
For CRDs where kubeconform reports “no schema found”, use the documentation from Stage 3 to manually validate spec fields.
Stage 5: Cluster Dry-Run (if available)
Try server-side dry-run first:
kubectl apply --dry-run=server -f <file.yaml>
Fallback logic:
- Connection error → try
--dry-run=clientand document “Limited validation (no cluster access)” - Validation error → record error, continue to Stage 6
- Parse error → skip client dry-run, continue to Stage 6
For updates:
kubectl diff -f <file.yaml>
Stage 6: Generate Detailed Validation Report (REPORT ONLY)
Constraint: Present the report and let the user take action — do NOT use the Edit tool or prompt the user to apply fixes.
Report structure:
- Issue summary table with severity, stage, location, issue, and suggested fix
- Severity categories: Errors (must fix), Warnings (should fix), Info (optional)
- Before/after code blocks for each issue with fix complexity: [Simple], [Medium], [Complex]
- Validation summary with stage status table and next steps
Example issue format:
**Issue 1: deployment.yaml:21 - Wrong field type (Error) [Simple]**
Current:
```yaml
- containerPort: "80"
Suggested Fix:
- containerPort: 80
## Best Practices Reference
Load when schema validation fails with type errors, reports missing required fields, or dry-run fails with validation errors:
Read references/k8s_best_practices.md
## Detailed Validation Workflow Reference
Load when the file contains 3+ resources, or validation produces unfamiliar errors spanning multiple stages:
Read references/validation_workflow.md
## Working with Multiple Resources
When a YAML file contains multiple resources (separated by `---`):
1. Validate the entire file first with yamllint and kubeconform
2. Identify which resource has issues by checking line numbers
3. For dry-run, the file is tested as a unit
4. Track issues per-resource in the report
**Partial parsing:** Tools parse valid documents and continue when some documents have syntax errors:
| Document | Resource | Parsing | Validation |
|----------|----------|---------|------------|
| 1 | Deployment | ❌ Syntax error (line 6) | Skipped |
| 2 | Service | ✅ Parsed | ✅ Valid |
| 3 | Certificate | ✅ Parsed | ✅ Valid |
**Always use file-absolute line numbers** (relative to the start of the entire file) — this matches what yamllint, kubeconform, and kubectl report, and lets users navigate directly to errors in their editor.
## Common Anti-Patterns
### NEVER: Skip Validation Because "It Looks Fine"
**BAD**:
```bash
# Directly applying without validation
kubectl apply -f deployment.yaml
GOOD:
# Validate first, apply only after clean report
yamllint deployment.yaml
kubeconform deployment.yaml
kubectl apply --dry-run=server -f deployment.yaml
# Then apply
kubectl apply -f deployment.yaml
NEVER: Fix Only the First Error
BAD:
# Fix syntax error on line 10, re-run, fix next error, repeat...
# This takes 10x longer than collecting all issues upfront
GOOD:
# Run full validation workflow once
# Fix all errors in one pass using the comprehensive report
# Re-validate to confirm clean
NEVER: Ignore Warnings
BAD:
# "It's just a warning, ship it"
apiVersion: extensions/v1beta1 # Deprecated API version
kind: Deployment
GOOD:
# Warnings indicate future breakage—fix them now
apiVersion: apps/v1
kind: Deployment
NEVER: Validate Against Wrong Kubernetes Version
BAD:
# Using default kubeconform schemas (may not match cluster version)
kubeconform deployment.yaml
GOOD:
# Always validate against target cluster version
kubectl version # Check cluster version
kubeconform -kubernetes-version 1.28.0 deployment.yaml
# Or use server-side dry-run (inherently correct)
kubectl apply --dry-run=server -f deployment.yaml
NEVER: Trust Client-Side Validation Alone
BAD:
kubectl apply --dry-run=client -f deployment.yaml # Misses cluster-specific issues
GOOD:
# Use server-side dry-run to catch admission webhooks, RBAC, quotas
kubectl apply --dry-run=server -f deployment.yaml
ALWAYS: Validate Multi-Resource Files as a Unit
CRD order matters (e.g., namespace before resources in that namespace):
# Validate the full file, not individual resources
kubectl apply --dry-run=server -f all-resources.yaml
ALWAYS: Check CRD Versions
# Verify CRD version matches what's installed in cluster
kubectl get crd <crd-name> -o jsonpath='{.spec.versions[*].name}'
Error Handling Strategies
Tool Not Available
- Run
scripts/setup_tools.shto check availability and get installation instructions - Skip optional stages but document what was skipped
Cluster Access Issues
- Fall back to client-side dry-run
- Document limitations in validation report
CRD Documentation Not Found
- Document the failed lookup
- Attempt validation with kubeconform CRD schemas
- Suggest manual inspection:
kubectl get crd <crd-name>.group -o yaml kubectl explain <kind>
Validation Stage Failures
- Continue to next stage even if one fails
- Collect all errors before presenting to user
- Prioritize fixing earlier stage errors first
Version Awareness
- Check for deprecated APIs (e.g.,
extensions/v1beta1→apps/v1) - For CRDs, ensure the apiVersion matches what’s in the cluster
- Use
kubectl api-versionsto list available API versions
Verification After Fixes
After the user applies fixes:
- Re-run full validation workflow to ensure clean report
- Verify zero errors in all stages (syntax, schema, dry-run)
- Check for new warnings introduced by fixes
- Test deployment in non-production environment first:
kubectl apply -f <file.yaml> --namespace=dev kubectl get <resource> -n dev -w # Watch for successful creation
Anti-Patterns
NEVER use only kubectl apply --dry-run=client for validation
- WHY: Client-side dry run only checks schema syntax locally; it does not contact the API server and misses server-side admission webhook rejections, quota violations, and custom resource validation.
- BAD:
kubectl apply --dry-run=client -f manifest.yamlas the sole validation step. - GOOD: Run
kubectl apply --dry-run=server -f manifest.yamlto include server-side validation against the real API server.
NEVER skip namespace-specific validation when resources use ClusterRole or PodSecurityAdmission
- WHY: Cluster-level policies differ by namespace; a manifest that validates in one namespace may be rejected in another due to different PodSecurity admission levels or RBAC configurations.
- BAD: Validate in the
defaultnamespace and deploy to a hardened production namespace without re-validating. - GOOD: Validate against the target namespace explicitly:
kubectl apply --dry-run=server --namespace=production -f manifest.yaml.
NEVER treat kubeconform/kubeval “unknown fields” warnings as acceptable for CRDs
- WHY: These warnings mean the schema is not available and validation of those fields was skipped entirely; unknown CRD fields can still cause runtime failures even when kubeconform exits 0.
- BAD: Ignore
--strictmode warnings for custom resources and ship the manifest assuming it is valid. - GOOD: Provide the CRD schema file with
--schema-locationso custom resource fields are validated:kubeconform --schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' --strict manifest.yaml.
NEVER validate manifests without also running a policy checker
- WHY: kubeconform validates schema but not best practices; Polaris or kube-score flags missing resource limits, missing liveness/readiness probes, privilege escalation, and host-path mounts that schema validation cannot detect.
- BAD: Pass kubeconform with zero errors and ship the manifest without policy scanning.
- GOOD: Run both kubeconform (schema) and Polaris or kube-score (policy) in the validation pipeline before applying to any cluster.
References
scripts/
detect_crd_wrapper.sh — Wrapper that manages Python dependencies (auto-creates venv if PyYAML unavailable) and calls detect_crd.py.
Usage: bash scripts/detect_crd_wrapper.sh <file.yaml>
detect_crd.py — Parses YAML files to identify CRDs; extracts kind, apiVersion, group, version; outputs JSON.
Usage: python3 scripts/detect_crd.py <file.yaml>
setup_tools.sh — Checks for required validation tools, reports versions, provides installation instructions.
Usage: bash scripts/setup_tools.sh
references/
k8s_best_practices.md — Kubernetes YAML best practices: metadata, labels, resource limits, security context, common validation issues.
validation_workflow.md — Detailed workflow, command options, error handling strategies, complete workflow diagram.
assets/
.yamllint — Pre-configured yamllint rules following Kubernetes conventions (2-space indentation, line length, etc.).
Usage: yamllint -c assets/.yamllint <file.yaml>
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Runtime validation via eval scenarios proving the skill actually changes agent behaviour. Requires evals/ directory, instructions.json, ≥3 scenarios, and ≥80% instruction coverage in summary.json.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Runtime validation via eval scenarios proving the skill actually changes agent behaviour. Requires evals/ directory, instructions.json, ≥3 scenarios, and ≥80% instruction coverage in summary.json.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
Expert-only knowledge the AI couldn't derive on its own — domain-specific patterns, production gotchas, decision frameworks, and non-obvious tool behaviour. High scores mean <5% redundancy with what the model already knows.
A clear philosophy plus numbered step-by-step workflows with explicit entry/exit points. Should answer: what is the core principle, how to execute it, and when (and when not) to apply it.
Explicit NEVER/WHY/consequence triplets with side-by-side bad/good examples. Generic warnings score low — concrete failure modes with real impact (security, correctness, performance) score high.
Proper frontmatter, single-task focus, activation keywords, and cross-harness portability. Skills must work across 40+ agentic harnesses without hardcoded paths or agent-specific references.
SKILL.md as a <100-line navigation hub pointing to focused references/ files. Content should be lazy-loaded on demand, not front-loaded. Includes actionable 'When to Use' conditions per reference.
Appropriate rigidity for the skill type: strict rules for critical/security skills, balanced steps for process skills, flexible options for tool skills. Mismatched calibration (too rigid or too loose) reduces score.
Rich activation keywords and trigger scenarios in the description so the skill fires when needed. Best descriptions read like an exhaustive list of the tasks and concepts that should invoke this skill.
Copy-paste-ready code, complete runnable examples, real file paths and commands. Pseudocode and abstract descriptions score low — concrete, executable content scores high.
Runtime validation via eval scenarios proving the skill actually changes agent behaviour. Requires evals/ directory, instructions.json, ≥3 scenarios, and ≥80% instruction coverage in summary.json.
No eval scenarios available.
Kubernetes YAML Best Practices
General YAML Best Practices
Formatting and Style
- Use 2 spaces for indentation (not tabs)
- Keep lines under 80 characters when possible
- Use lowercase for keys
- Quote string values containing special characters
- Always specify apiVersion and kind
- Include metadata.name for all resources
Resource Organization
- One resource per file for clarity (unless logically grouped)
- Use
---to separate multiple resources in a single file - Name files descriptively:
<resource-type>-<name>.yaml
Kubernetes-Specific Best Practices
Metadata
metadata:
name: my-app
namespace: production
labels:
app: my-app
version: v1.0.0
component: backend
managed-by: kubectl
annotations:
description: "Backend service for my-app"
Labels and Selectors
- Always include
applabel - Use consistent label keys across resources
- Include version labels for rollout tracking
- Selectors must match pod labels exactly
Resource Limits and Requests
Always specify both requests and limits:
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
Probes
Always define liveness and readiness probes:
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
Security
securityContext:
runAsNonRoot: true
runAsUser: 1000
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
Image Management
image: registry.example.com/my-app:v1.2.3 # Always use specific tags
imagePullPolicy: IfNotPresent # Or Always for :latest
Common Validation Issues
Missing Required Fields
apiVersionandkindare always requiredmetadata.nameis required for all resourcesspec.selectormust be specified for Deployments/Servicesspec.template.spec.containersmust have at least one container
Selector Mismatches
Deployment selector must match pod template labels:
# Deployment
spec:
selector:
matchLabels:
app: my-app # Must match pod labels below
template:
metadata:
labels:
app: my-app # Must match selector above
Invalid Values
- CPU: Use millicore notation (e.g., “500m”) or fractional (e.g., “0.5”)
- Memory: Use Mi, Gi notation (e.g., “512Mi”)
- Port numbers: Must be 1-65535
- DNS names: Must be lowercase alphanumeric with hyphens
Namespace Issues
- Not all resources are namespaced (e.g., ClusterRole, PersistentVolume)
- Services must be in the same namespace as the pods they target
- Default namespace is “default” if not specified
CRD-Specific Considerations
API Version Compatibility
- Check the CRD version installed in the cluster
- Use the correct apiVersion for the CRD
- Be aware of deprecations (e.g., v1alpha1 → v1beta1 → v1)
Required Fields
- CRDs often have custom required fields in spec
- Check the CRD documentation for field requirements
- Use
kubectl explain <kind>to see field documentation
Validation
- CRDs may have custom validation rules
- OpenAPI schema validation is stricter in newer K8s versions
- Use dry-run to catch validation errors before applying
Deprecation Warnings
Common Deprecated APIs
extensions/v1beta1→apps/v1(Deployments, DaemonSets)networking.k8s.io/v1beta1→networking.k8s.io/v1(Ingress)policy/v1beta1→policy/v1(PodDisruptionBudget)
Always use the latest stable API version.
Kubernetes YAML Validation Workflow
This document outlines the comprehensive validation workflow for Kubernetes YAML resources.
Validation Stages
Stage 1: YAML Syntax Validation (yamllint)
Purpose: Catch YAML syntax errors and style issues before Kubernetes-specific validation.
Command:
yamllint <file.yaml>
Common Issues Detected:
- Indentation errors (tabs vs spaces)
- Line length violations
- Trailing spaces
- Missing document start markers
- Duplicate keys
- Syntax errors
Configuration:
Create a .yamllint config file for custom rules:
extends: default
rules:
line-length:
max: 120
indentation:
spaces: 2
comments:
min-spaces-from-content: 1
Stage 2: Kubernetes Schema Validation (kubeconform)
Purpose: Validate against Kubernetes schemas and detect structural issues.
Basic Command:
kubeconform -summary <file.yaml>
With CRD Support (recommended):
kubeconform \
-schema-location default \
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \
-strict \
-ignore-missing-schemas \
-summary \
-verbose \
<file.yaml>
Options:
-strict: Reject resources with unknown fields (catches typos - recommended for production)-ignore-missing-schemas: Skip validation for CRDs without available schemas-kubernetes-version <version>: Validate against specific K8s version (e.g., 1.30.0)-output json: Output results as JSON
Common Issues Detected:
- Invalid apiVersion
- Missing required fields
- Invalid field types
- Unknown fields (in strict mode)
- Invalid enum values
Stage 3: Cluster Dry-Run (kubectl)
Purpose: Validate against the actual cluster configuration, admission controllers, and policies.
Client-Side Dry Run:
kubectl apply --dry-run=client -f <file.yaml>
- Validates against basic Kubernetes API rules
- Does not contact the cluster
- Fast but less thorough
Server-Side Dry Run:
kubectl apply --dry-run=server -f <file.yaml>
- Full validation including admission controllers
- Validates against cluster-specific constraints
- Requires cluster access
- Catches issues like:
- Resource quota violations
- Policy violations (PSP, OPA, Kyverno)
- Admission webhook rejections
- Namespace existence
- ConfigMap/Secret references
Diff Mode (for updates):
kubectl diff -f <file.yaml>
Shows what would change if applied to the cluster.
CRD Detection and Documentation Lookup
Step 1: Detect CRDs
Use the detect_crd.py script:
python3 scripts/detect_crd.py <file.yaml>
Output example:
[
{
"kind": "Certificate",
"apiVersion": "cert-manager.io/v1",
"group": "cert-manager.io",
"version": "v1",
"isCRD": true,
"name": "example-cert"
}
]
Step 2: Lookup CRD Documentation
For each detected CRD:
-
Look up the CRD documentation:
- Run
kubectl explain <kind>.specwhen the CRD is installed in a reachable cluster, or search the project’s documentation with the query:"<project> <kind> <version> specification" - Example:
"cert-manager Certificate v1 spec fields and validation" - Focus on the specific version for compatibility
- Run
-
Fallback to Web Search:
- Search query:
"<kind>" "<group>" kubernetes CRD "<version>" documentation - Example:
"Certificate" "cert-manager.io" kubernetes CRD "v1" documentation - Look for official documentation sites
- Check for API references and examples
- Search query:
Step 3: Validate Against CRD Schema
Once documentation is found:
- Check required fields in spec
- Verify field types and formats
- Validate enum values
- Check for version-specific changes
Complete Validation Workflow
┌─────────────────────────────────────────────────────────────┐
│ 1. Check Tools │
│ Run: scripts/setup_tools.sh │
│ Ensure yamllint, kubeconform, kubectl are installed │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 2. YAML Syntax Check │
│ Run: yamllint <file.yaml> │
│ Fix: Indentation, trailing spaces, syntax errors │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 3. Detect CRDs │
│ Run: python3 scripts/detect_crd.py <file.yaml> │
│ Parse: Extract kind, apiVersion, group │
└─────────────────────────────────────────────────────────────┘
↓
┌──────┴──────┐
│ │
[CRD?] [Standard Resource]
│ │
↓ ↓
┌──────────────────────┐ │
│ 4a. Lookup CRD Docs │ │
│ - Library docs │ │
│ - Web search │ │
│ - Version-aware │ │
└──────────────────────┘ │
│ │
└──────┬──────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 5. Schema Validation │
│ Run: kubeconform -summary <file.yaml> │
│ Fix: Required fields, types, unknown fields │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 6. Dry-Run (if cluster available) │
│ Run: kubectl apply --dry-run=server -f <file.yaml> │
│ Fix: Admission issues, quotas, policies │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 7. Generate Validation Report │
│ - Summarize all issues in table format │
│ - Show before/after code blocks for each issue │
│ - Do NOT modify files - report only │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 8. Provide Next Steps │
│ - List errors that must be fixed │
│ - List warnings for best practices │
│ - User decides which fixes to apply │
└─────────────────────────────────────────────────────────────┘
Error Handling
Tool Not Found
- Run
scripts/setup_tools.shto check tool availability - Provide installation instructions
- Skip optional validation stages if tools missing
Cluster Not Available
- Skip server-side dry-run
- Use client-side dry-run and kubeconform instead
- Warn user that some validations are skipped
CRD Documentation Not Found
- Document that CRD docs couldn’t be found
- Attempt validation with kubeconform CRD schemas
- Suggest checking cluster for CRD definition:
kubectl get crd <crd-name> -o yaml
Multiple Resources in One File
- Validate each resource separately
- Track which resource has issues
- Provide line numbers for error locations
Best Practices for Validation
- Always validate in order: syntax → schema → dry-run
- Collect all issues: Don’t stop at first error - gather everything before reporting
- For CRDs: Always look up documentation first
- Version awareness: Check K8s version compatibility
- Test with cluster: Server-side dry-run is the most reliable
- Show before/after: Display code blocks showing suggested fixes
- Provide context: Explain what each issue means and why the fix is needed
- Report only: Do NOT modify files - let user decide which fixes to apply
- Load best practices reference: When schema errors occur, load k8s_best_practices.md for context
Creating Validation Reports
Generate a comprehensive validation report with all findings. Do NOT modify files.
Report Components
-
Header with issue count
## Validation Report - 7 issues found (4 errors, 3 warnings) -
Issues Summary Table
| Severity | Stage | Location | Issue | Suggested Fix | |----------|-------|----------|-------|---------------| | Error | Syntax | file.yaml:8 | Wrong indentation | Use 2 spaces | | Error | Schema | file.yaml:21 | Wrong type | Change to integer | | Warning | Best Practice | file.yaml:30 | Missing labels | Add app label | -
Detailed Findings (for each issue)
- File:line reference
- Current code block
- Suggested fix code block
- Explanation of why it matters
-
Validation status by stage
- Show which stages passed/failed
- Note if any stages were skipped (e.g., no cluster access)
-
Next Steps
- List errors that must be fixed before deployment
- List warnings for best practices consideration
- Suggest re-running validation after fixes
Example Report Format
## Validation Report - 7 issues found
File: deployment.yaml
Resources Analyzed: 3 (Deployment, Service, Certificate)
| Stage | Status | Issues |
|-------|--------|--------|
| YAML Syntax | ❌ Failed | 2 errors |
| CRD Detection | ✅ Passed | 1 CRD found |
| Schema Validation | ❌ Failed | 2 errors |
| Dry-Run | ❌ Failed | 1 error |
### Issue 1: deployment.yaml:8 - Wrong indentation (Error)
Current:
```yaml
labels:
```
Suggested Fix:
```yaml
labels:
```
**Why:** Kubernetes YAML requires 2-space indentation.
### Issue 2: deployment.yaml:21 - Wrong field type (Error)
Current:
```yaml
- containerPort: "80"
```
Suggested Fix:
```yaml
- containerPort: 80
```
**Why:** containerPort must be an integer, not a string.
[... more issues ...]
## Next Steps
1. Fix the 4 errors listed above (deployment will fail without these)
2. Consider addressing the 3 warnings for best practices
3. Re-run validation to confirm all issues resolved
Report Best Practices
- Be specific: List every issue with exact location
- Show both current and suggested: Always show before/after code blocks
- Explain impact: Help user understand why each issue matters
- Group by file: When multiple files are involved
- Prioritize by severity: Errors first, then warnings, then info
- Provide file references: Always include file:line for traceability
- Clear next steps: Tell user exactly what to do