Inferensys

Prompt

Terraform Apply Error Recovery Prompt

A practical prompt playbook for using Terraform Apply Error Recovery Prompt in production AI workflows to diagnose and fix provider, state, and configuration errors.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the specific job-to-be-done, the ideal user, and the operational boundaries for the Terraform Apply Error Recovery Prompt.

This prompt is designed for infrastructure engineers and platform teams who are blocked by a failed terraform plan or terraform apply and need to move past the error quickly. The ideal user is someone who can read a Terraform configuration and an error message but needs assistance reasoning about the underlying provider API contract, state file integrity, or resource dependency graph that caused the failure. The job-to-be-done is not just to get a corrected block of HCL, but to receive a root-cause explanation that builds the engineer's mental model of the failure, enabling them to prevent similar issues in the future. You should use this prompt when the error is non-trivial—meaning it is not a simple typo, a missing variable, or a copy-paste mistake that a linter would catch.

The prompt requires two concrete inputs to be effective: the exact Terraform configuration block that is failing, and the complete, unredacted error output from the terraform CLI. Without both, the model lacks the context to distinguish between a provider version mismatch, a state lock contention, a misconfigured remote backend, or an API-level validation error from the cloud provider. The prompt instructs the model to act as a senior infrastructure engineer, which means it should prioritize fixes that are idempotent, respect existing resource dependencies, and do not introduce destructive changes like forced re-creation unless explicitly justified. The harness that wraps this prompt should immediately pipe the corrected configuration into terraform validate and a targeted terraform plan to confirm the fix is syntactically valid and produces a non-destructive diff.

Do not use this prompt for initial architecture design, for generating new Terraform modules from scratch, or for errors caused by external network partitions that no configuration change can resolve. It is also inappropriate for failures where the root cause is a manual state manipulation (terraform state rm/import) that has left the state file inconsistent in a way that requires a human operator to decide on a reconciliation strategy. In those cases, the prompt may produce a plausible-looking fix that masks the underlying state corruption. The next step after reading this section is to gather your failing configuration and error output, then proceed to the prompt template to begin the recovery loop.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Terraform Apply Error Recovery Prompt is the right tool for your infrastructure workflow.

01

Good Fit: Provider or State Errors

Use when: terraform apply fails with a clear provider error, state lock conflict, or resource dependency issue. The prompt excels at interpreting Terraform-specific error messages and mapping them to configuration fixes. Guardrail: Always run terraform validate and terraform plan on the corrected configuration before applying.

02

Bad Fit: Multi-Resource Refactors

Avoid when: the error is a symptom of a broader architectural change requiring updates across dozens of resources, modules, or state migrations. The prompt is designed for targeted fixes, not large-scale refactors. Guardrail: For complex refactors, break the problem into smaller, sequential recovery steps or escalate to a human operator.

03

Required Inputs: Error and Configuration

Must provide: the full terraform apply error output (including line references), the relevant .tf files, and the Terraform version. Without the exact error text and source configuration, the prompt cannot produce a reliable fix. Guardrail: Include the terraform plan output if available to give the model additional context about the intended changes.

04

Operational Risk: Drift and Side Effects

Risk: the corrected configuration may resolve the immediate error but introduce resource drift or unintended destruction of existing infrastructure. Guardrail: Always review the terraform plan output of the corrected configuration for unexpected resource deletions or modifications before applying.

05

Operational Risk: State File Corruption

Risk: errors involving state file locks or corruption may require state manipulation commands (terraform state rm, terraform import) that the prompt cannot safely execute. Guardrail: If the error suggests state corruption, escalate to a human operator with access to state management commands and backups.

06

Good Fit: CI/CD Pipeline Failures

Use when: a Terraform apply fails inside an automated pipeline (GitHub Actions, GitLab CI, Jenkins) and the error log is captured. The prompt can produce a corrected configuration that can be committed and re-triggered. Guardrail: Ensure the pipeline includes a terraform plan step on the PR branch before merging the fix.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for diagnosing and correcting Terraform apply errors, ready to be wired into an AI harness.

The following prompt template is designed to be pasted directly into your AI harness. It instructs the model to act as a senior infrastructure engineer, consuming a failed Terraform configuration and its error output to produce a corrected configuration and a clear diagnosis. The template uses square-bracket placeholders for all dynamic inputs, ensuring you can swap in the specific error, configuration, and constraints for your incident. Before using this in a production pipeline, you must replace every placeholder with the actual values from your failed run. The prompt is self-contained: it includes the required role, the input schema, the expected output structure, and explicit constraints that prevent the model from introducing new resources or making unauthorized changes.

text
You are a senior infrastructure engineer specializing in Terraform and cloud provider APIs. Your task is to diagnose a failed `terraform apply` or `terraform plan` operation and produce a corrected version of the configuration.

## INPUT
You will receive the following:
- **Original Configuration**: The Terraform HCL that was applied.
  ```hcl
  [FAILED_TERRAFORM_CONFIGURATION]
  • Error Output: The full error message from the Terraform CLI.
    text
    [TERRAFORM_ERROR_OUTPUT]
  • Provider Context: The provider and version in use.
    text
    [PROVIDER_NAME_AND_VERSION]
  • State Context (optional): A summary of the relevant existing state, if the error involves a state mismatch.
    text
    [RELEVANT_STATE_SUMMARY]

TASK

  1. Diagnose the root cause: Identify whether the error is a syntax issue, a provider API constraint violation, a state mismatch, a dependency ordering problem, or a resource naming conflict.
  2. Produce a corrected configuration: Output the full, corrected HCL for the affected resources. Do not omit any original resource blocks unless they are the direct cause of the error and must be removed.
  3. Explain the fix: Provide a concise, step-by-step explanation of what was changed and why, referencing the specific error message.

CONSTRAINTS

  • Do not add new resources, data sources, or providers that were not in the original configuration.
  • Do not change resource names or identifiers unless the error is a naming conflict that requires it.
  • Preserve all existing comments and formatting where possible.
  • If the error is a state mismatch, do not suggest terraform import or state manipulation commands unless explicitly allowed by [ALLOW_STATE_COMMANDS].
  • If the error is a provider bug or an API limitation, suggest a practical workaround and flag it with # WORKAROUND: [reason].
  • If you cannot determine a safe fix with the provided information, respond with a structured uncertainty report instead of guessing.

OUTPUT FORMAT

Respond in JSON with the following structure:

json
{
  "diagnosis": {
    "error_category": "syntax_error | provider_constraint | state_mismatch | dependency_error | naming_conflict | unknown",
    "root_cause": "A concise description of the root cause, referencing the error message.",
    "affected_resources": ["list", "of", "resource", "addresses"]
  },
  "corrected_configuration": "The full corrected HCL as a single string.",
  "explanation": [
    "Step 1: What was changed and why.",
    "Step 2: ..."
  ],
  "uncertainty_report": null  // Or an object with "reason" and "suggested_next_steps" if the fix is uncertain.
}

RISK LEVEL

[RISK_LEVEL: low | medium | high]

  • If RISK_LEVEL is "high", include a # REVIEW REQUIRED comment on every changed line and add a human_review_notes field to the output JSON explaining what an engineer must verify before applying.

To adapt this template for your environment, start by replacing the core placeholders: [FAILED_TERRAFORM_CONFIGURATION] and [TERRAFORM_ERROR_OUTPUT] must come directly from your CI/CD logs or local terminal. The [PROVIDER_NAME_AND_VERSION] placeholder should be populated from your required_providers block or the .terraform.lock.hcl file. The [RELEVANT_STATE_SUMMARY] is optional but critical for state-mismatch errors; you can generate it by running terraform state list and terraform state show on the affected resources. The [ALLOW_STATE_COMMANDS] boolean should be set to true only if your harness is permitted to suggest terraform state rm or terraform import commands; in most production pipelines, this should be false to prevent unsafe state manipulation. The [RISK_LEVEL] placeholder should be set dynamically based on the blast radius of the affected resources—for example, changes to network ACLs, IAM policies, or database instances should be marked as high.

When wiring this prompt into an application, ensure the harness validates the model's output before applying any changes. The corrected configuration must pass terraform validate and a targeted terraform plan against the original state. If the plan shows unexpected resource destruction or recreation, the harness should block the change and escalate for human review. For high-risk changes, the harness should automatically append a # REVIEW REQUIRED comment to every modified line and create a pull request rather than applying directly. Never allow an AI-generated fix to be applied to production infrastructure without a human approval gate when RISK_LEVEL is high.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Terraform Apply Error Recovery Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how the harness should check the input before execution.

PlaceholderPurposeExampleValidation Notes

[TERRAFORM_CONFIG]

The full HCL content of the failing Terraform configuration file

resource "aws_s3_bucket" "main" { ... }

Parse check: must be valid HCL syntax. If empty or null, abort prompt and return error to caller.

[ERROR_OUTPUT]

The complete stderr and stdout from the failed terraform apply or plan command

Error: creating S3 bucket: BucketAlreadyExists: ...

Parse check: must contain a recognized Terraform error pattern. If no error pattern detected, route to human review.

[TERRAFORM_VERSION]

The version of Terraform used in the execution environment

1.6.2

Schema check: must match semver pattern. If null, default to latest stable and note the assumption in the output.

[PROVIDER_LOCK_FILE]

The contents of the .terraform.lock.hcl file for provider version constraints

provider "registry.terraform.io/hashicorp/aws" { version = "5.0" ... }

Parse check: must be valid HCL. If null, the prompt must instruct the model to note that provider versions are unverified.

[STATE_ERROR_CONTEXT]

Any state-related error details from the Terraform state file or backend

Error: state lock already held by run-abc123

Null allowed. If present, must be a string. If the error involves state lock, the prompt must include a warning about manual lock release.

[TARGET_RESOURCE]

The specific resource address that failed, extracted from the error output

aws_s3_bucket.main

Parse check: must match Terraform resource address pattern. If null, the prompt must instruct the model to infer the target from the error context.

[EXECUTION_MODE]

The Terraform command that failed: plan, apply, or destroy

apply

Enum check: must be one of plan, apply, destroy. If null or invalid, default to apply and note the assumption.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Terraform Apply Error Recovery Prompt into a CI/CD pipeline or operator workflow with validation, retries, and safe rollback.

The Terraform Apply Error Recovery Prompt is designed to sit inside a remediation step that triggers only after terraform apply or terraform plan returns a non-zero exit code. The harness captures the full error output, the original Terraform configuration files, and any relevant state or provider context before invoking the model. This prompt is not a replacement for terraform validate or terraform fmt; it is a recovery tool for semantic and provider-level errors that static checks cannot catch, such as resource conflicts, missing dependencies, or API-side validation failures.

Wire the prompt into a pipeline stage that runs after a failed apply. The input assembly step must collect: the exact error message from stderr, the content of the offending .tf files, the Terraform and provider versions, and the target workspace or environment name. After the model returns a corrected configuration, the harness must run terraform validate on the proposed fix. If validation passes, execute terraform plan in a non-destructive mode (e.g., with -target scoped to the affected resource) and diff the plan against the expected state. Only if the plan is clean and contains no unexpected deletions should the fix proceed to a manual approval gate or an automated apply in non-production environments. Log every recovery attempt, including the original error, the model's suggested fix, the validation result, and the plan diff, for audit and regression testing.

Set a strict retry budget: no more than two recovery attempts per failed apply. If the first fix fails validation or produces a plan with destructive changes, feed the new error back to the model with the updated context and allow one more attempt. After two failures, escalate to a human operator and attach the full log trail. For production environments, always require a human to approve the plan before applying the corrected configuration. Avoid running this recovery loop against stateful resources like databases or persistent volumes without a snapshot or backup step preceding the retry. The most common failure mode is the model suggesting a resource recreation when an in-place update or state import would suffice; the plan diff review catches this before it reaches production.

IMPLEMENTATION TABLE

Expected Output Contract

The harness must validate the model's JSON response against this contract before applying any Terraform fix. Reject responses that fail schema validation and trigger a retry or escalation.

Field or ElementType or FormatRequiredValidation Rule

corrected_configuration

string

Must be valid HCL. Validate with terraform validate in a temp dir. Reject if the command exits non-zero.

error_diagnosis

object

Must contain root_cause (string) and provider_or_state_issue (string). Both must be non-empty after trimming.

error_diagnosis.affected_resources

array of strings

Each element must match the Terraform resource address pattern resource_type.resource_name. At least one element required.

fix_explanation

string

Must be 50-2000 characters. Must reference specific lines or blocks from [ERROR_OUTPUT] and [ORIGINAL_CONFIG].

validation_checks

array of objects

Each object must have command (string, one of 'terraform validate', 'terraform plan', 'terraform fmt') and expected_result (string, one of 'success', 'no changes', 'no errors'). Array must not be empty.

breaking_change_risk

string

Must be one of 'none', 'low', 'medium', 'high'. If 'high', the requires_approval field must be true.

requires_approval

boolean

Must be true if breaking_change_risk is 'high' or if the fix modifies stateful resources (e.g., databases, persistent volumes). Otherwise false.

targeted_plan_command

string

Must be a valid terraform plan command string targeting the affected resources. Must start with 'terraform plan' and include -target flags.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using a Terraform Apply Error Recovery Prompt and how to guard against it in production infrastructure pipelines.

01

Hallucinated Provider Arguments

What to watch: The model invents resource arguments or provider features that don't exist in the installed provider version, producing a syntactically valid but semantically broken fix. Guardrail: Always run terraform validate on the corrected configuration and diff the proposed changes against the provider schema documentation before applying.

02

State Drift from Incomplete Fixes

What to watch: The prompt corrects the immediate error but ignores resources already created or modified in state, causing a mismatch between the proposed fix and real-world infrastructure. Guardrail: Require a terraform plan on the corrected configuration and compare the planned changes against the expected state delta. Flag any unexpected destroy or recreate actions for human review.

03

Sensitive Value Leakage in Error Context

What to watch: Terraform error messages often include sensitive values like connection strings, secrets, or private IPs. Passing the raw error into the prompt may expose secrets to the model provider. Guardrail: Redact sensitive fields from the error output before including it in the prompt context. Use a pre-processing step that masks values matching known secret patterns or Terraform sensitive variable markers.

04

Provider Version Mismatch Assumptions

What to watch: The model assumes a newer or different provider version than what is pinned in the configuration, suggesting arguments or resource types that are unavailable. Guardrail: Include the required_providers block and provider version constraints in the prompt context. Validate the corrected configuration against the locked provider version using terraform providers lock output.

05

Cyclic Dependency Introduction

What to watch: The fix introduces a circular dependency between resources that passes terraform validate but fails at plan or apply time with a cycle error. Guardrail: After generating the fix, run terraform graph and check for cycles programmatically. Flag any new dependency edges that create bidirectional references between resources.

06

Blind Apply Without Human Review

What to watch: The pipeline automatically applies the model's corrected configuration without human approval, potentially destroying or modifying critical infrastructure based on a hallucinated fix. Guardrail: Gate all model-generated Terraform changes behind a manual approval step. Require a human to review the diff, the plan output, and the model's explanation before any apply proceeds in production environments.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of the Terraform Apply Error Recovery Prompt output before integrating it into an automated pipeline. Each row defines a specific testable standard.

CriterionPass StandardFailure SignalTest Method

Configuration Validity

The corrected Terraform configuration passes terraform validate without errors.

terraform validate returns an error or warning related to the new configuration.

Automated: Run terraform validate on the outputted configuration block.

Error Resolution

The fix directly addresses the root cause described in the original [ERROR_MESSAGE].

The original error persists when applying the fix, or a new, unrelated error is introduced.

Automated: Execute a targeted terraform plan for the changed resource and confirm the original error is absent.

No State Drift

The terraform plan for the fix shows only the intended changes and no unexpected resource destruction or modification.

The plan output includes -/+ destroy and then create replacement for an unrelated resource or other unintended state changes.

Automated: Parse the terraform plan output in JSON format and check for unexpected resource actions.

Provider Correctness

The fix uses valid arguments and correct syntax for the specific provider and resource type mentioned in the error.

The fix uses a deprecated argument, an incorrect resource type, or a syntax not supported by the provider version.

Automated: Validate the resource schema against the provider's public documentation or a local provider schema dump.

Explanation Quality

The [EXPLANATION] output clearly states the root cause, the fix applied, and the specific provider or state behavior that caused the error.

The explanation is generic (e.g., 'fixed a syntax error'), hallucinates a provider behavior, or does not reference the original error.

LLM-as-Judge: Use a rubric to check if the explanation references the [ERROR_MESSAGE] and the specific resource attribute changed.

Idempotency

Applying the same prompt with the same [ERROR_MESSAGE] and [CONFIGURATION] produces a functionally identical fix.

Subsequent runs produce a different fix or suggest further, unnecessary changes to the configuration.

Automated: Run the prompt twice and use a diff tool to compare the outputted configurations.

Security Posture

The fix does not introduce overly permissive security group rules, hard-coded secrets, or public exposure of private resources.

The corrected configuration opens a security group to 0.0.0.0/0 unnecessarily or exposes a private database endpoint.

Automated: Scan the outputted configuration with a policy-as-code tool like Open Policy Agent (OPA) or Checkov.

Minimal Fix Principle

The output changes only the minimum number of lines required to resolve the error.

The output rewrites large, unrelated blocks of the configuration or reformats the entire file.

Manual Review: Use a standard diff tool to compare the input [CONFIGURATION] with the outputted configuration.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single Terraform error and config. Skip the terraform validate harness step. Focus on getting a plausible fix explanation, not a guaranteed-apply correction.

Prompt modification

  • Remove the [OUTPUT_SCHEMA] constraint; accept free-text fix + explanation.
  • Replace [CONSTRAINTS] with a single line: "Explain the error and suggest a fix."
  • Drop the [PREVIOUS_ATTEMPTS] placeholder if this is the first try.

Watch for

  • Provider version mismatches that the model doesn't flag
  • Fixes that pass terraform validate but destroy state
  • Overly broad resource recreation suggestions
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.