# terraform-codegen

Part of **TERRAFORM**

# Terraform Code Generation Troubleshooting Guide

## Problem Index

| Problem | Symptom | Severity | Solution Summary |
|--------|--------|----------|------------------|
| Invalid Terraform Syntax | Error: `Invalid expression` or `Missing required argument` | High | Regenerate with clearer prompt or validate against Terraform schema |
| Unsupported or Hallucinated Resource | Error: `Unsupported block type` or `Reference to undeclared resource` | High | Verify resource exists in provider docs; avoid ambiguous requests |
| Generation Timeout or Truncation | Response cuts off mid-block or hangs during streaming | Medium | Reduce prompt complexity or retry with shorter context |
| Incorrect Attribute Assignment | Error: `Invalid or unknown key` in resource block | Medium | Specify exact attribute names from official documentation |
| Model Misinterprets Intent | Generated code does not match user request | Low | Refine prompt with explicit examples or constraints |

## Problem Details

### Problem 1: Invalid Terraform Syntax

**Symptoms**
- Error message: `Invalid expression`
- Error message: `Missing required argument`
- Behavior: `terraform validate` fails immediately after code generation
- Context: Occurs when the AI generates malformed HCL (HashiCorp Configuration Language)

**Root Cause**
- The LLM may omit required arguments, misplace brackets, or use incorrect interpolation syntax due to ambiguous prompts or model limitations.
- Terraform’s strict HCL parser rejects even minor syntactic deviations.

**Solution**
1. Review the generated code for missing commas, braces, or required fields like `name`, `region`, or `engine`.
2. Run validation locally:
   ```bash
   terraform init
   terraform validate
   ```
3. If errors persist, re-prompt the Copilot with a more structured request, e.g., “Generate a complete aws_db_instance block with all required arguments for MySQL 8.0.”
4. Cross-check syntax against the official Terraform registry documentation for the target resource.

**Verification**
- `terraform validate` returns: `Success! The configuration is valid.`
- No parsing errors during `terraform plan`

### Problem 2: Unsupported or Hallucinated Resource

**Symptoms**
- Error message: `Unsupported block type`
- Error message: `Reference to undeclared resource`
- Behavior: Terraform reports that a resource type (e.g., `alicloud_rds_mysql_v2`) does not exist
- Context: Common when requesting niche or version-specific resources not in the model’s training data

**Root Cause**
- The LLM may “hallucinate” resource types that sound plausible but are not part of the actual Terraform provider.
- The Copilot lacks real-time access to provider schemas and relies on static knowledge.

**Solution**
1. Confirm the correct resource name using the official Terraform provider documentation.
2. Avoid vague terms like “new RDS instance” — instead specify: “alicloud_db_instance with engine MySQL”
3. If the resource truly doesn’t exist, adjust your request to use a supported equivalent.
4. Use multi-turn conversation to clarify: “What RDS resources are available for Alibaba Cloud?”

**Verification**
- The resource type appears in the provider’s published documentation
- `terraform providers schema -json` includes the resource type

### Problem 3: Generation Timeout or Truncation

**Symptoms**
- Response ends abruptly mid-resource block (e.g., cuts off after `settings {`)
- Streaming output stalls or stops before completion
- Context: Occurs with long or complex prompts exceeding model context window

**Root Cause**
- The LLM has a fixed context window; overly detailed prompts leave insufficient space for full output.
- Streaming may terminate early due to internal timeout or token limits.

**Solution**
1. Simplify your prompt: break complex requests into smaller, focused ones (e.g., generate VPC first, then RDS).
2. Avoid including large code snippets or irrelevant background in the prompt.
3. Retry the request with a concise version: “Generate only the alicloud_db_instance block for production MySQL”
4. If using a UI, check for a “Regenerate” or “Continue” option after truncation.

**Verification**
- Full, syntactically complete resource block is returned
- No ellipses (`...`) or incomplete braces in output

### Problem 4: Incorrect Attribute Assignment

**Symptoms**
- Error message: `Invalid or unknown key`
- Behavior: Terraform accepts the config but fails during apply with unexpected values
- Context: AI uses plausible-sounding but non-existent attribute names (e.g., `db_version` instead of `engine_version`)

**Root Cause**
- The model infers attribute names from natural language but may not map them precisely to the provider’s API.
- Similar-sounding attributes across cloud providers cause confusion.

**Solution**
1. Identify the incorrect attribute from the Terraform error log.
2. Consult the official resource documentation for the exact attribute name and type.
3. Reprompt with explicit guidance: “Use only attributes from the alicloud_db_instance documentation. Set engine_version, not db_version.”
4. Validate attributes using `terraform console` for dynamic expressions if needed.

**Verification**
- `terraform plan` shows expected values without warnings
- Attribute appears in provider schema under `terraform providers schema`

### Problem 5: Model Misinterprets Intent

**Symptoms**
- Generated code creates a different resource than requested (e.g., PostgreSQL instead of MySQL)
- Omits critical constraints like backup retention or network isolation
- Context: Ambiguous or underspecified prompts

**Root Cause**
- The LLM fills gaps in intent with defaults or assumptions not aligned with user needs.
- Lack of explicit parameters leads to generic or demo-style output.

**Solution**
1. Restate your request with explicit parameters:
   > “Create an alicloud_db_instance with engine MySQL 8.0, backup_retention_period = 7, and vswitch_id = vsw-xxxx”
2. Use examples in your prompt: “Like this: resource 'alicloud_db_instance' 'example' { ... }”
3. Engage in multi-turn refinement: ask follow-up questions like “Did you include encryption?”
4. Avoid open-ended phrases like “set up a database” — be specific about topology and compliance needs.

**Verification**
- Generated code matches all specified parameters
- No unexpected defaults (e.g., public accessibility enabled when not requested)

## FAQ

**Q: How do I verify that the AI-generated Terraform code is correct?**  
A: Always run `terraform init` followed by `terraform validate`. Then review `terraform plan` to confirm resources and settings match expectations before applying.

**Q: Why does the Copilot sometimes invent resources that don’t exist?**  
A: The underlying LLM generates text based on patterns, not live API schemas. It may produce plausible but invalid resource types. Always cross-check against official provider documentation.

**Q: Can I improve generation accuracy with better prompts?**  
A: Yes. Use precise, structured prompts that include resource type, required attributes, and constraints. Example: “Generate a complete alicloud_db_instance block for MySQL 8.0 in VPC vpc-123 with 100GB storage.”

**Q: What should I do if the response is cut off?**  
A: Simplify your request to reduce token usage, then retry. Avoid pasting large existing configs into the prompt unless necessary.

**Q: Is there a way to see what Terraform resources are supported?**  
A: Yes. Use `terraform providers schema -json` after initializing your configuration, or consult the official Terraform Registry for your provider.