Inferensys

Prompt

Kubernetes Manifest YAML Repair Prompt Template

A practical prompt playbook for using the Kubernetes Manifest YAML Repair Prompt Template in production AI workflows. Repairs indentation, apiVersion mismatches, kind field errors, and spec structure violations with a dry-run validation gate and diff against the last known good manifest.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required context, and constraints for the Kubernetes Manifest YAML Repair Prompt Template.

This prompt is designed for platform engineers and DevOps practitioners who need to repair model-generated Kubernetes YAML manifests that fail kubectl apply --dry-run=client validation. The job-to-be-done is straightforward: take a malformed manifest and a reference to the last known good state, and produce a syntactically valid, structurally correct manifest that passes a dry-run gate. The ideal user is someone who already understands Kubernetes resource schemas and is integrating an LLM into a GitOps pipeline, a developer self-service portal, or an internal platform that generates infrastructure configuration. You should use this prompt when the model output is structurally broken—indentation errors, apiVersion mismatches, missing or malformed kind fields, or spec structure violations—but the intent of the manifest is still recoverable.

Do not use this prompt when the manifest is syntactically valid but semantically wrong (e.g., a correctly formed Deployment that references a non-existent ConfigMap). That class of error requires a different workflow involving cluster state queries and resource dependency resolution, not structural repair. This prompt also assumes you have a last-known-good manifest or a reference template to diff against. If you are generating manifests from scratch without any reference, use a schema-first generation prompt from the Structured Output and Schema Control pillar instead. The repair prompt works best when the damage is local—a few lines of broken YAML—rather than a completely hallucinated resource definition. For high-risk production environments, always pair this prompt with a kubectl apply --dry-run=server validation step and a human approval gate before the manifest reaches a live cluster.

Before wiring this into your pipeline, ensure you have a reliable way to capture the failed manifest, the validation error message from kubectl, and the last known good version of the same resource. The prompt uses these three inputs to constrain the repair and prevent the model from inventing fields or values that were never present. If you lack a last-known-good manifest, you can substitute a reference template from your organization's approved resource catalog, but be aware that the repair quality will degrade. After running the repair, always diff the output against the last known good manifest to verify that only the broken sections were modified. This diff serves as both a quality check and an audit trail for your change control process.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Kubernetes Manifest YAML Repair prompt works, where it fails, and what you must have in place before relying on it in a production or CI/CD pipeline.

01

Good Fit: Near-Miss Syntax Errors

Use when: The model-generated YAML is structurally recognizable but fails kubectl apply --dry-run=server due to common issues like indentation drift, tab-space mixing, or a single incorrect apiVersion. Guardrail: Always run the repair output through --dry-run=server and kubeconform before applying; never apply directly from the model's response.

02

Bad Fit: Missing or Hallucinated Spec Logic

Avoid when: The manifest has missing entire spec sections, invented resource properties, or incorrect RBAC rules that require deep Kubernetes knowledge. Guardrail: Use a diff against a known-good manifest from the target namespace. If the repair prompt must invent more than 20% of the spec, escalate to a human platform engineer.

03

Required Input: Last Known Good Manifest

Risk: Without a reference manifest, the model may repair syntax while silently changing resource limits, selectors, or volume mounts. Guardrail: Always provide a [LAST_KNOWN_GOOD_MANIFEST] as a diff baseline. The prompt should output a structural diff alongside the repaired YAML so reviewers can see what changed beyond whitespace.

04

Required Input: Exact Validation Error

Risk: Feeding the model a broken YAML without the specific kubectl or parser error forces it to guess what is wrong, increasing hallucination risk. Guardrail: Always include the raw [VALIDATION_ERROR] string as context. The repair prompt should explain how each fix addresses a specific error line before outputting the corrected manifest.

05

Operational Risk: Silent Selector Drift

Risk: The model may "fix" indentation in a way that changes label selectors, causing a Deployment to orphan Pods or match unintended Services. Guardrail: Add a post-repair validation step that extracts and compares spec.selector.matchLabels against the last known good manifest. Fail the repair if selectors change without explicit approval.

06

Operational Risk: Applying in Production Pipelines

Risk: Auto-applying repaired manifests in a GitOps pipeline can propagate a subtle spec change across clusters before a human notices. Guardrail: The repair prompt output must be staged as a PR, not directly committed. Require a human or a strict policy-as-code gate (e.g., OPA/Kyverno) to approve any diff beyond whitespace before merge.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for repairing malformed Kubernetes YAML manifests with placeholders for input, context, and validation constraints.

This prompt template is designed to be copied directly into your application code or prompt management system. It accepts a failed Kubernetes manifest and a kubectl error message, then produces a repaired YAML manifest that passes kubectl apply --dry-run=client validation. The template uses square-bracket placeholders for all variable inputs—replace these with actual values at runtime before sending the prompt to the model.

text
You are a Kubernetes YAML repair specialist. Your task is to fix a malformed Kubernetes manifest that failed `kubectl apply`.

## INPUT
Failed manifest YAML:
```yaml
[FAILED_MANIFEST_YAML]

Error message from kubectl:

code
[KUBECTL_ERROR_OUTPUT]

CONSTRAINTS

  • Output ONLY the repaired YAML manifest inside a single fenced code block labeled yaml.
  • Do not include explanations, apologies, or commentary outside the code block.
  • Preserve all original resource definitions unless they are structurally invalid.
  • Fix the following error classes in priority order:
    1. Indentation errors (tabs, inconsistent spaces, misaligned blocks).
    2. apiVersion mismatches (correct to match the kind field using stable API versions).
    3. kind field errors (case sensitivity, missing kind, invalid kind values).
    4. spec structure violations (missing required fields, wrong field types, invalid nesting).
    5. metadata issues (missing name, invalid labels/annotations format).
  • If a field value is ambiguous and cannot be inferred from context, use the placeholder REQUIRES_MANUAL_REVIEW and do not guess.
  • Do not add new resources, containers, or configuration that was not present in the original manifest.
  • Normalize indentation to 2-space increments.

OUTPUT FORMAT

yaml
[REPAIRED_MANIFEST_YAML]

VALIDATION CHECK

After generating the output, mentally verify:

  • Every apiVersion matches the correct group and version for its kind.
  • metadata.name is present and follows DNS subdomain naming rules.
  • spec contains all required fields for the resource kind.
  • Indentation is consistent throughout.

To adapt this template for your environment, replace [FAILED_MANIFEST_YAML] with the raw YAML string that failed validation, and [KUBECTL_ERROR_OUTPUT] with the exact error text returned by kubectl. If you have a last-known-good manifest for the same resource, prepend it as additional context with a ## REFERENCE section to help the model preserve intentional configuration choices. For high-risk production clusters, always route the repaired output through a human approval step before applying—this prompt is a repair aid, not a replacement for cluster change review. Wire the output through a YAML parser and kubectl --dry-run=client in your application harness before accepting the repair as complete.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Kubernetes Manifest YAML Repair Prompt. Each variable must be supplied or explicitly set to null before the prompt is assembled. Missing or malformed inputs are the most common cause of repair failure.

PlaceholderPurposeExampleValidation Notes

[BROKEN_YAML]

The raw, malformed Kubernetes manifest YAML that failed kubectl apply or a YAML parser

apiVersion: apps/v1 kind: Deployment name: nginx ...

Must be a non-empty string. Validate that the input contains YAML-like structure before invoking repair. Null not allowed.

[ERROR_MESSAGE]

The exact error output from kubectl apply, kubeval, or the YAML parser

error: error parsing deploy.yaml: error converting YAML to JSON: yaml: line 4: mapping values are not allowed in this context

Must be a non-empty string. The repair prompt uses this to localize the fault. If no error message is available, set to 'No parser error available; perform structural validation only.'

[LAST_KNOWN_GOOD_MANIFEST]

The most recent valid version of this manifest for diff comparison

apiVersion: apps/v1 kind: Deployment metadata: name: nginx spec: replicas: 3 ...

Optional. Set to null if no prior version exists. When provided, must be valid YAML. The prompt uses this to detect regressions and avoid hallucinating removed fields.

[TARGET_NAMESPACE]

The Kubernetes namespace the manifest is intended for

production

Optional. Set to null if not applicable. When provided, must be a valid RFC 1123 DNS label. The prompt uses this to validate namespace references in the manifest.

[KUBERNETES_VERSION]

The target cluster version for apiVersion compatibility checks

1.29

Optional. Set to null if unknown. When provided, must match semver pattern. The prompt uses this to flag deprecated or removed apiVersions.

[REPAIR_STRATEGY]

Controls how aggressively the prompt should modify the manifest

conservative

Must be one of: 'conservative' (fix only what is broken, preserve intent), 'normalize' (fix and apply style conventions), or 'minimal' (smallest possible diff to achieve parse validity). Defaults to 'conservative' if null.

[DRY_RUN_OUTPUT]

The output from kubectl apply --dry-run=server for pre-repair validation

Error from server (BadRequest): container spec.template.spec.containers[0].image: Required value

Optional. Set to null if dry-run was not performed. When provided, the prompt uses server-side validation errors to guide repairs beyond syntax.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Kubernetes Manifest YAML Repair prompt into a production-grade validation and repair pipeline.

This prompt is designed to be the final repair step in a kubectl apply failure loop, not a standalone YAML generator. The application harness should catch the initial kubectl error, extract the raw model output and the specific error message, and then invoke this prompt with the [FAILED_MANIFEST] and [KUBECTL_ERROR] placeholders populated. The prompt's primary job is to produce a corrected manifest that passes a --dry-run=client validation gate. Do not use this prompt for generating new manifests from scratch; it is a targeted repair tool for manifests that are structurally close to valid but contain indentation errors, apiVersion mismatches, missing required fields under spec, or incorrect kind values.

The implementation loop should follow a strict sequence: (1) The application receives a model-generated YAML string. (2) It attempts kubectl apply --dry-run=client -f -. (3) On failure, capture the exit code and stderr. (4) If the error is a syntax or schema validation error (not an RBAC or cluster-state error), call the LLM with this repair prompt, injecting the failed manifest and the raw error text. (5) Take the LLM's output and run it through a YAML parser (e.g., Python's yaml.safe_load) to catch basic formatting errors. (6) Re-run kubectl apply --dry-run=client on the repaired output. (7) If the dry-run succeeds, return the repaired manifest to the caller; if it fails again, increment a retry counter. After three failed repair attempts, log the full failure context and escalate to a human operator or a dead-letter queue. Never apply a repaired manifest directly to a live cluster without a successful dry-run gate.

For high-risk environments, add a diff step between the last known good manifest and the repaired output to highlight structural changes. Log every repair attempt with the model's response, the dry-run result, and a diff against the original failed input. Choose a model with strong code and configuration reasoning (e.g., Claude 3.5 Sonnet or GPT-4o) and set the temperature low (0.0–0.1) to minimize creative deviations. Avoid using this harness for manifests that fail due to missing CRDs or cluster-scoped resources; those errors indicate a missing dependency, not a YAML syntax problem, and should be routed to a different resolution workflow.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure, types, and validation rules for the repaired Kubernetes manifest YAML. Use this contract to programmatically gate the output before passing it to kubectl apply --dry-run=client.

Field or ElementType or FormatRequiredValidation Rule

apiVersion

string (e.g., apps/v1)

Must match a valid Kubernetes apiVersion from [TARGET_API_GROUP]. Parse check: non-empty string with group/version format.

kind

string (e.g., Deployment)

Must exactly match [TARGET_KIND]. Case-sensitive string equality check.

metadata.name

string

Must conform to RFC 1123 subdomain. Regex: ^a-z0-9?$. Length <= 253.

metadata.namespace

string

If present, must conform to RFC 1123 label. If absent, default namespace is assumed by kubectl.

spec

object

Must be a non-null object. Structure must match the OpenAPI v3 schema for [TARGET_KIND] in [TARGET_API_GROUP].

spec.template.spec.containers

array

Must be a non-empty array. Each element must have 'name' (string) and 'image' (string) fields. Array length >= 1.

status

object

If present, must be stripped from the output. The manifest is for apply, not read. Presence triggers a removal rule.

diff_summary

string

If [LAST_KNOWN_GOOD_MANIFEST] is provided, a human-readable summary of structural changes must be appended as a YAML comment only.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using an LLM to repair Kubernetes manifests and how to guard against it.

01

Silent Spec Drift

What to watch: The model 'repairs' the YAML so it passes kubectl --dry-run=client but silently changes replica counts, resource limits, or environment variables to plausible but incorrect values. Guardrail: Always diff the repaired manifest against the last known good version and flag any numeric or string changes outside the broken sections.

02

Hallucinated API Versions

What to watch: The model replaces a deprecated or mismatched apiVersion with one that doesn't exist in your cluster version, causing a different failure. Guardrail: Validate the repaired apiVersion and kind against a cluster capability report (kubectl api-resources) before applying.

03

Indentation Cascade Failure

What to watch: A single indentation error in a nested spec (e.g., container args) causes the model to restructure the entire document, introducing new errors in previously valid sections. Guardrail: Instruct the model to make the minimal structural change and use a strict YAML round-trip parser to verify only the broken lines were touched.

04

Comment and Annotation Stripping

What to watch: The repair prompt strips critical comments, deployment annotations (e.g., kubectl.kubernetes.io/last-applied-configuration), or custom labels that other operators depend on. Guardrail: Explicitly instruct the model to preserve all comments and metadata annotations, and verify their presence in the output.

05

Multi-Document Confusion

What to watch: A multi-document YAML stream (---) with one broken resource causes the model to merge, reorder, or drop the other valid documents. Guardrail: Split the input into individual documents, repair only the failing one, and reassemble. Validate the document count matches the input.

06

Over-Confident Repair of Unknown Fields

What to watch: The model encounters a CRD field it doesn't recognize and either removes it or fills it with a hallucinated structure to 'fix' the schema. Guardrail: Instruct the model to preserve unknown fields verbatim and only repair structural YAML errors, not semantic content it cannot validate.

IMPLEMENTATION TABLE

Evaluation Rubric

Test criteria for evaluating the quality and safety of repaired Kubernetes manifests before applying them to a cluster. Use this rubric in an automated eval harness or manual review gate.

CriterionPass StandardFailure SignalTest Method

kubectl dry-run acceptance

kubectl apply --dry-run=server exits 0 with no errors

Exit code non-zero; error message contains 'error:', 'invalid', or 'unrecognized'

Execute kubectl apply --dry-run=server -f [REPAIRED_MANIFEST] in sandbox cluster context

apiVersion/kind alignment

apiVersion matches the correct group/version for the declared kind per Kubernetes API

apiVersion is deprecated, nonexistent, or mismatched to kind (e.g., apps/v1beta1 for Deployment)

Validate apiVersion against Kubernetes API reference for the declared kind; check deprecation status

Spec structure completeness

All required fields for the resource kind are present and non-null per Kubernetes schema

Missing required fields such as spec.containers for Pod, spec.selector for Deployment, or spec.rules for Ingress

Validate against Kubernetes OpenAPI schema for the resource kind; check required field presence

Indentation and whitespace validity

YAML parses without indentation errors; consistent 2-space indentation; no tab characters

YAML parser throws 'mapping values are not allowed here', 'block mapping expected', or tab character detected

Parse with strict YAML parser (e.g., Python ruamel.yaml or kubectl --validate); scan for tab characters

No hallucinated fields or values

All fields and values in the repaired manifest derive from [ORIGINAL_MANIFEST] or standard Kubernetes defaults

Fields appear that were not in original manifest and are not required defaults; invented container names, ports, or labels

Diff repaired manifest against original; flag any added fields not in Kubernetes default schema; human review for invented values

Container image and tag preservation

All container image references match [ORIGINAL_MANIFEST] exactly; no tag changes or registry substitutions

Image tag changed from original; registry hostname altered; digest removed or replaced

Exact string match of spec.containers[].image and spec.initContainers[].image against original manifest

Resource quota and limit retention

spec.containers[*].resources.requests and limits match original values; no removal or arbitrary scaling

Resource requests or limits removed, set to zero, or changed from original values without explicit instruction

Deep equality check of resources block per container against original manifest

Security context and policy preservation

securityContext fields from original manifest are retained; no privilege escalation or restriction removal

privileged: true added; runAsNonRoot removed; capabilities added without authorization; seccompProfile removed

Diff securityContext at pod and container level against original; flag any elevation of privilege or removal of restrictions

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a lightweight dry-run gate. Drop the diff-against-last-known-good step and focus on kubectl apply --dry-run=client as the sole validation. Accept any output that passes dry-run without structural inspection.

yaml
[MANIFEST_TO_REPAIR]

Watch for

  • Dry-run passing does not guarantee semantic correctness
  • apiVersion deprecations may be missed without cluster version context
  • No guard against hallucinated resource names or labels
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.