Inferensys

Prompt

Terraform HCL Configuration Block Repair Prompt

A practical prompt playbook for using Terraform HCL Configuration Block Repair Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the exact conditions, required inputs, and boundaries for using the Terraform HCL repair prompt in a production pipeline.

This prompt is for infrastructure engineers and platform teams who receive model-generated Terraform configurations that fail terraform validate or terraform plan. It repairs syntax errors, missing required arguments, block structure violations, and resource dependency issues in HCL. Use this prompt when a model has produced a configuration that is structurally close to valid but contains specific, identifiable errors that prevent parsing or planning. This is a post-generation repair step, not a configuration generation prompt. It assumes you already have a malformed HCL block and the corresponding error output from Terraform's own validation tooling. The prompt instructs the model to act as a strict repair agent: it must not add new resources, change resource names, or alter the intended infrastructure topology. It must only fix what is broken and return a valid, parseable HCL block.

The ideal workflow wires this prompt into a CI/CD pipeline or an internal platform API. After an initial model generates a Terraform configuration, run terraform validate or terraform plan. If the command exits with a non-zero status, capture the malformed HCL and the exact error output. Feed both into this prompt as [MALFORMED_HCL] and [TERRAFORM_ERROR_OUTPUT]. The model returns a repaired HCL block. You must then run terraform validate on the repaired output before accepting it. If validation fails again, you can retry once with the new error output, but set a hard limit of two repair attempts before escalating to a human operator. Never apply a repaired configuration without a passing terraform plan review.

Do not use this prompt when the model has hallucinated entire resources that don't exist, invented provider features, or produced a configuration that is semantically wrong but syntactically valid. This prompt cannot fix logic errors like wrong CIDR blocks, incorrect IAM policy bindings, or security group rules that open unintended ports. It also cannot recover configurations that are so badly malformed that the original intent is unreadable. In those cases, discard the output and regenerate from the original intent prompt. This prompt is a precision repair tool, not a garbage collector. Use it when the error is specific, the fix is local, and the infrastructure topology is already correct.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and what you must provide before using it in a production infrastructure pipeline.

01

Good Fit: Post-Generation Repair Loop

Use when: A model has already generated Terraform HCL that fails terraform validate or terraform plan due to syntax errors, missing required arguments, or block structure violations. Guardrail: Always run the output through terraform validate before applying. This prompt repairs, it does not architect.

02

Bad Fit: Greenfield Module Authoring

Avoid when: You need to design a new Terraform module from scratch, choose between resource types, or make architectural decisions. Guardrail: Use architecture review prompts for design. This prompt assumes the intended resource graph is already known and only the HCL syntax is broken.

03

Required Input: Failing HCL and Validation Error

Must provide: The malformed HCL block and the exact error output from terraform validate. Guardrail: Without the validation error message, the model must guess what is broken. Always include the full error text to enable targeted repair rather than speculative rewriting.

04

Required Input: Provider and Resource Documentation

Must provide: Relevant provider version and resource argument reference if the error involves missing or deprecated arguments. Guardrail: The model's training cutoff may not include recent provider changes. Ground repairs against current docs to avoid replacing one error with another.

05

Operational Risk: Silent Drift from Intent

Risk: The repair may produce valid HCL that passes validation but changes resource behavior—different instance types, missing tags, altered dependency ordering. Guardrail: Always diff the repaired output against the original broken input and review semantic changes, not just syntax fixes. Run terraform plan and review the plan output before apply.

06

Operational Risk: Dependency Graph Corruption

Risk: Repairing block structure may break depends_on references, interpolated resource attributes, or data source lookups. Guardrail: After repair, run terraform graph or review the plan's dependency ordering. Flag any resource that lost its dependency edge for manual review.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for repairing model-generated Terraform HCL configuration blocks.

This prompt template is designed to be pasted directly into your repair harness. It accepts a broken or invalid Terraform HCL block, the specific error output from terraform validate, and optional context about the intended infrastructure. The model is instructed to act as a strict HCL syntax and structure repair agent, not a creative infrastructure designer. It must produce a corrected block that passes validation without introducing new resources, changing resource types, or hallucinating arguments that were not present in the original broken input.

text
You are an HCL repair agent. Your only job is to fix Terraform configuration blocks so they pass `terraform validate`.

## INPUT
[BROKEN_HCL_BLOCK]

## VALIDATION ERROR
[VALIDATION_ERROR_OUTPUT]

## PROVIDER CONTEXT
Provider: [PROVIDER_NAME]
Provider Version: [PROVIDER_VERSION]

## REPAIR RULES
1. Fix only the errors reported in the validation output. Do not restructure working parts of the configuration.
2. Never change resource types, names, or identifiers.
3. Never add new resources, data sources, or provider blocks.
4. If a required argument is missing, add it with a placeholder value wrapped in angle brackets: <REQUIRED>.
5. If an argument value is invalid, correct it to the nearest valid value based on the provider documentation for version [PROVIDER_VERSION].
6. Preserve all existing comments unless they interfere with syntax repair.
7. If the block contains resource dependencies (depends_on, references to other resources), verify they reference resources that exist in the provided context. Flag unresolvable references in a `## DEPENDENCY_WARNINGS` section.
8. Output only the repaired HCL block and the dependency warnings section. No explanations, no markdown fences around the HCL.

## OUTPUT FORMAT
```hcl
<repaired_hcl_block>

DEPENDENCY_WARNINGS

  • <warning_item> or "No dependency issues detected."

CONSTRAINTS

  • Do not explain your changes.
  • Do not add commentary outside the output format.
  • If the block cannot be repaired with the information provided, output ## REPAIR_FAILED followed by the specific reason.

To adapt this template, replace the square-bracket placeholders with your actual values. [BROKEN_HCL_BLOCK] should contain the raw, malformed HCL. [VALIDATION_ERROR_OUTPUT] must be the exact error text from terraform validate—this is critical because the model uses error line numbers and messages to target its repairs. [PROVIDER_NAME] and [PROVIDER_VERSION] ground the model in the correct provider schema, reducing hallucinations of nonexistent arguments. If you are repairing a block that references other resources in the same module, include those resource definitions in [BROKEN_HCL_BLOCK] or supply them as additional context so the dependency check in rule 7 can function. For high-risk infrastructure changes, always run the repaired output through terraform plan in a non-production workspace and require human approval before apply.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Terraform HCL Configuration Block Repair Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is well-formed before use.

PlaceholderPurposeExampleValidation Notes

[BROKEN_HCL]

The malformed Terraform configuration block that failed validation or parsing

resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" subnet_id = aws_subnet.public.id tags = { Name = "WebServer" } }

Must be non-empty string. Verify it contains at least one HCL block delimiter (resource, data, module, provider, variable, output, locals, terraform). Reject if input is valid HCL that passes terraform validate.

[VALIDATION_ERROR]

The exact error output from terraform validate, terraform fmt -check, or HCL parser

Error: Missing required argument on main.tf line 14, in resource "aws_instance" "web": 14: resource "aws_instance" "web" {

The argument "subnet_id" is required, but no definition was found.

Must be non-empty string. Should contain line numbers, error type, and message. If error output is empty, the repair prompt cannot target specific failures. Parse for known error patterns: 'Missing required argument', 'Invalid value', 'Unsupported argument', 'Invalid block definition'.

[PROVIDER_SCHEMA]

Provider and resource type documentation or schema reference for required arguments and valid block structure

resource "aws_instance" { required: ami, instance_type optional: subnet_id, vpc_security_group_ids, tags, ... blocks: ebs_block_device, network_interface, ... }

Must include at minimum: resource type name, list of required arguments, and valid block types. Can be extracted from terraform providers schema -json output. If null, the model can only repair syntax errors, not missing-argument errors. Validate that provider name and resource type match [BROKEN_HCL].

[RESOURCE_DEPENDENCIES]

Map of referenced resources, data sources, and variables that must exist in the broader configuration

{ "aws_subnet.public": { "type": "resource", "provider": "aws" }, "var.environment": { "type": "variable" } }

Optional but strongly recommended. Must be valid JSON object. Each key must be a valid Terraform reference pattern (resource_type.name, data.source_type.name, var.name, local.name, module.name.output). If null, the model cannot verify that referenced resources exist, increasing risk of unresolved reference errors.

[CONFIGURATION_CONTEXT]

Surrounding configuration blocks from the same module that provide dependency and variable context

variable "environment" { type = string default = "staging" }

data "aws_vpc" "main" { id = "vpc-abc123" }

Optional. Must be valid HCL or empty string. If provided, must parse without errors. Helps the model resolve variable references, data source lookups, and module outputs referenced in [BROKEN_HCL]. If null, the model repairs in isolation and may produce references that fail cross-resource validation.

[TERRAFORM_VERSION]

The Terraform CLI version constraint for syntax and feature compatibility

1.6.0

Must match semver pattern (X.Y.Z). If null, assume latest stable. Controls whether the model uses deprecated syntax (e.g., interpolation-only expressions in 0.11 vs 0.12+ HCL2). Validate against terraform version -json output if available.

[REPAIR_STRATEGY]

Directive for how aggressively the model should repair vs preserve original intent

conservative

Must be one of: conservative (fix only what's broken, preserve original structure), balanced (fix errors and improve style within reason), aggressive (full restructure to best practices). If null, default to conservative. Controls whether the model rewrites working blocks or only touches failing lines.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Terraform HCL repair prompt into a CI pipeline or infrastructure automation workflow with validation gates, retry logic, and human review for high-risk changes.

This prompt is designed to sit inside a post-generation repair loop, not as a standalone chat interaction. The typical integration point is a CI/CD pipeline or infrastructure-as-code automation workflow where a model generates or modifies Terraform configurations and the output fails terraform validate or terraform plan. Instead of discarding the output, the failed HCL block and the validation error are passed to this prompt for structured repair. The harness must capture the original model output, the exact terraform validate error message, the target provider and resource type context, and any known variable values or module references before invoking the repair prompt.

The implementation loop follows a strict sequence: (1) capture the raw model-generated HCL and run terraform validate -json to get structured error output; (2) extract the failing block, the error message, and the line number range; (3) assemble the prompt with [FAILED_HCL_BLOCK], [VALIDATION_ERROR], [PROVIDER_CONTEXT], and [RESOURCE_CONSTRAINTS]; (4) call the model with a low temperature (0.0–0.2) to maximize deterministic repair behavior; (5) parse the repaired HCL from the response, write it to a temporary .tf file, and re-run terraform validate; (6) if validation passes, run terraform plan to check for unexpected resource changes or dependency breaks; (7) if validation fails again, increment a retry counter and re-invoke the prompt with the new error—stop after three retries and escalate to a human operator. Each repair attempt must be logged with the input error, the model's response, and the validation result for auditability.

For high-risk environments—production infrastructure, stateful resources, or security group changes—add a mandatory human approval gate after successful validation but before terraform apply. The harness should generate a diff between the original failed HCL and the repaired version, present it alongside the terraform plan output, and require explicit approval. Do not auto-apply repaired configurations to production without review. For lower-risk environments like development namespaces or ephemeral test infrastructure, you can auto-apply after validation and plan pass, but still log the full repair chain. Model choice matters: use a model with strong code generation capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) and avoid small or general-purpose models that may introduce new syntax errors during repair. If your workflow uses OpenTofu instead of Terraform, substitute tofu validate in the validation gate—the prompt structure remains identical.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact structure, types, and validation rules for the repaired Terraform HCL output. Use this contract to build a post-processing validator that gates the output before it reaches any plan or apply step.

Field or ElementType or FormatRequiredValidation Rule

repaired_hcl

String (HCL)

Must parse successfully with a standard HCL2 parser. No syntax errors, unclosed braces, or illegal tokens allowed.

repair_summary

Array of Objects

Each object must contain 'line' (integer), 'issue' (string from [ISSUE_TAXONOMY]), and 'action' (string). Array must not be empty if any repair was made.

repair_summary[].line

Integer

Must be a positive integer corresponding to the line number in the original [BROKEN_HCL] input where the issue was detected.

repair_summary[].issue

String (Enum)

Must match one of the values in [ISSUE_TAXONOMY], e.g., 'missing_required_argument', 'syntax_error', 'block_structure_violation', 'resource_dependency_error'.

repair_summary[].action

String

A concise, human-readable description of the fix applied. Must not be an empty string.

terraform_validate_result

String (Enum)

Must be exactly 'pass' or 'fail'. If 'fail', the 'repaired_hcl' field should be an empty string and 'repair_summary' must contain the blocking error.

resource_dependency_check

Object

Must contain 'status' (enum: 'valid', 'warning', 'error') and 'details' (string). If 'error', 'terraform_validate_result' must be 'fail'.

resource_dependency_check.status

String (Enum)

Must be 'valid', 'warning', or 'error'. 'error' indicates a broken dependency that prevents a valid plan.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when repairing model-generated Terraform HCL and how to guard against it in production.

01

Syntax Repair Introduces Resource Drift

What to watch: The repair prompt fixes HCL syntax but silently changes resource names, attribute values, or dependency ordering, causing the repaired config to represent different infrastructure than the original intent. Guardrail: Diff the repaired HCL against the original malformed input before applying. Require terraform plan output review for any resource marked for recreation.

02

Missing Required Provider Arguments

What to watch: The model repairs block structure but omits required provider-level arguments like region, project, or subscription_id that were absent from the original broken config. Guardrail: Validate the repaired HCL against the provider schema using terraform validate and a provider requirements checklist. Flag any resource with empty required fields for human review.

03

Hallucinated Resource Attributes

What to watch: When the original config has missing or ambiguous values, the repair prompt invents plausible attribute values (e.g., AMI IDs, CIDR blocks, instance types) rather than leaving them as placeholders. Guardrail: Require the prompt to output [NEEDS_VALUE] tokens for any attribute it cannot derive from the original input. Post-process to flag all unresolved tokens before apply.

04

Dependency Graph Breakage

What to watch: Repairing block structure can reorder resources or rename references, breaking implicit and explicit dependencies (depends_on, interpolated attributes) that terraform validate does not always catch. Guardrail: Run terraform graph after repair and compare the dependency tree against a known-good reference or the original config's intended relationships. Flag any orphaned or newly introduced dependency edges.

05

State File Incompatibility

What to watch: The repaired config passes terraform validate but references resources already managed in state under different identifiers, causing import failures or orphaned state entries. Guardrail: Run terraform plan against the target state file or workspace. Require a state compatibility check that verifies all terraform import-able resources match existing state addresses before apply.

06

Sensitive Value Exposure in Repair Output

What to watch: The repair prompt may surface sensitive values (secrets, tokens, connection strings) that were malformed in the original config, exposing them in plaintext repair output or logs. Guardrail: Redact or mask sensitive arguments before sending to the model. Use variable references and sensitive = true markers in the repaired output. Never log the full repaired HCL without sanitization.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the repaired Terraform HCL output before integrating it into a CI/CD pipeline. Each criterion targets a specific failure mode of model-generated configuration blocks.

CriterionPass StandardFailure SignalTest Method

Syntax Validity

Output parses without errors using terraform validate or hcl2json

Parser throws syntax error, unexpected token, or illegal character

Automated: Run terraform validate -json on the output file. Check for zero diagnostics with error severity.

Required Arguments

All required arguments for the resource type are present and non-null

Missing required argument error from terraform validate or schema check

Automated: Extract resource type, fetch provider schema, diff required attributes against output keys. Fail if any required key is absent.

Block Structure Integrity

Nested blocks have correct opening/closing braces and valid labels

Mismatched braces, missing block labels, or blocks placed in wrong parent

Automated: Parse HCL to AST. Verify brace balance, block type nesting rules, and label count per block type.

Resource Dependency Correctness

All resource references resolve to resources defined in [CONTEXT] or the repaired block itself

Reference to undefined resource, circular dependency, or self-reference in depends_on

Automated: Extract all references with regex resource_type.resource_name. Diff against known resources in [CONTEXT]. Fail on unresolved references.

Attribute Value Type Match

Each attribute value matches the expected type from the provider schema

Type mismatch error from terraform validate or schema check

Automated: Fetch provider schema types. Check output values with type assertion. Flag string where bool expected, list where map expected, etc.

No Hallucinated Resources

Output contains only the resource type specified in [TARGET_RESOURCE_TYPE] and no invented resources

Additional resource blocks, data sources, or provider blocks not present in [ORIGINAL_BLOCK]

Automated: Count resource blocks in output. Fail if count differs from [ORIGINAL_BLOCK] or if resource types don't match [TARGET_RESOURCE_TYPE].

Expression and Function Validity

All HCL expressions and function calls use valid syntax and available functions

terraform validate reports function not found, invalid expression, or interpolation error

Automated: Run terraform validate. Check for diagnostics containing 'Call to unknown function' or 'Invalid expression'.

Idempotent Repair

Running the repair prompt twice on the same input produces semantically identical HCL

Second repair introduces new changes, reorders blocks unnecessarily, or alters values

Manual + Automated: Run repair twice. Normalize whitespace. Diff the two outputs. Fail if semantic differences exist beyond formatting.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single [HCL_BLOCK] input and the [PROVIDER_VERSION] constraint. Skip the diff output and focus on getting a parseable result. Run terraform fmt and terraform validate manually after generation. Accept that the model may miss provider-specific argument constraints.

Watch for

  • Missing required arguments that terraform validate catches but the model doesn't
  • Hallucinated resource types or attribute names from newer provider versions
  • Silent acceptance of deprecated argument forms
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.