Treating AI-Written Terraform as a Draft, Not a Plan to Apply

Close-up of cables and servers in a data center rack, representing infrastructure as code

AI models are useful for Terraform when you treat their output as a draft that must pass terraform fmt, terraform validate, a linter and a human review of terraform plan before anything is applied. The prompts that work best state the provider and version constraints, the naming and tagging conventions, and the security baseline up front, and ask the model to flag any argument it is not sure exists. This guide gives copy-ready prompts for writing new resources, building modules, reviewing a plan, refactoring safely with moved blocks and debugging errors, plus the mistakes AI-generated infrastructure code tends to make.

Infrastructure as code (IaC) means describing servers, networks, permissions and other cloud resources in version-controlled files instead of clicking through a console. Terraform is a widely used IaC tool from HashiCorp; OpenTofu is an open-source fork with a largely compatible language. The prompts below are written for Terraform’s HCL syntax and should work with minor wording changes for OpenTofu.

Why Terraform is a risky place to trust an AI blindly

A wrong line of application code usually fails a test. A wrong line of Terraform can delete a database, open a security group to the internet or rotate a resource that other systems depend on. Three properties of IaC make AI mistakes more costly here than elsewhere:

  • Provider schemas change. Cloud providers add, rename and deprecate resource arguments across major provider versions. A model trained on older examples can produce arguments that no longer exist, or the older way of configuring a resource that has since been split into separate resources.
  • Plans hide in the details. A one-character change in a resource name or an immutable argument can turn an in-place update into destroy-and-recreate.
  • Secrets end up in state. According to HashiCorp’s documentation on input variables, marking a variable sensitive hides it from CLI output, but Terraform still stores the value in state. A model that tells you sensitive = true “protects the secret” is giving you half the story.

None of this means you should not use AI for Terraform. It means the workflow around the prompt matters more than the prompt.

The context block to reuse in every prompt

Most of the quality gain comes from a reusable block of facts about your environment. Write it once, keep it in your repository and paste it above every task-specific prompt.

<terraform_context>
Terraform CLI: >= [1.x]   (or OpenTofu [version])
Providers (from our required_providers block):
  [hashicorp/aws ~> X.Y], [hashicorp/random ~> X.Y]
Cloud / region: [AWS eu-west-1]
State backend: [S3 + DynamoDB lock / Terraform Cloud / azurerm]
File layout: terraform.tf, providers.tf, main.tf, variables.tf,
  outputs.tf, locals.tf
Naming: resource labels are descriptive nouns in snake_case and do not
  repeat the resource type. Cloud names use "[org]-[env]-[purpose]".
Tags required on every taggable resource: owner, environment, cost_center
  (applied via provider default_tags where supported).
Security baseline:
  - no 0.0.0.0/0 ingress except ports 80/443 on public load balancers
  - encryption at rest on every storage service, customer-managed keys
    for [list]
  - no IAM wildcards ("*") in actions or resources without a comment
    explaining why
  - secrets come from [Secrets Manager / Key Vault], never from
    variables with defaults
</terraform_context>

The file layout and naming lines follow HashiCorp’s Terraform style guide, which recommends separate files for the terraform block, providers, variables and outputs, alphabetical ordering of variables and outputs, and resource names that do not repeat the resource type. Stating them explicitly stops the model from inventing its own conventions in every answer. If you already maintain a repository instructions file for an AI coding assistant, this block belongs there; our checklist for a Copilot instructions file shows how to structure one.

Prompt 1: Write a new resource or stack

[paste <terraform_context>]

Task: write Terraform for [an S3 bucket for application logs with a
90-day expiration, versioning on, public access fully blocked, and
server-side encryption with our KMS key module.kms.key_arn].

Requirements:
- Follow the file layout in the context; tell me which file each block
  goes into.
- Every variable has a type and a description; optional ones have a
  sensible default. Do not add variables for values that will not
  change between environments.
- Use for_each over a map when creating several similar resources with
  different settings; use count only for identical copies or 0/1
  conditional creation.
- Use only arguments and resource types that exist in the provider
  version range in the context. If you are not certain an argument
  exists in that range, mark the line with  # VERIFY  and say why.
- No hard-coded account IDs, ARNs or secrets.

After the code, list:
1. Every resource that will be created, one line each.
2. Any assumption you made about existing infrastructure.
3. Which lines a security reviewer should look at first.

Why each requirement is there

  • The # VERIFY marker gives the model a way to express uncertainty about provider arguments instead of inventing one confidently. It also gives you a search term for review.
  • The for_each/count rule mirrors the style guide’s advice: count for nearly identical resources, for_each when instances need distinct values. It matters later, because removing an item from the middle of a count list shifts indexes and can cause unexpected replacements.
  • “Do not add variables for values that will not change” counters a common AI habit of turning every string into a variable, which makes modules hard to read.
  • The three closing lists turn a block of HCL into something you can review: what gets created, what was assumed, and where risk concentrates.

Prompt 2: Turn copy-pasted code into a module

Repeated blocks across environments are the usual reason to write a module. Ask for the interface first, before any implementation, so you agree on inputs and outputs:

[paste <terraform_context>]

Below are the [dev] and [prod] versions of our [VPC] configuration.
Design a reusable module for it.

Step 1 (stop after this and wait for my approval):
- Propose the variables (name, type, description, default) and outputs.
- Explain which differences between dev and prod become variables and
  which should stay fixed inside the module.

Step 2 (after I approve):
- Write the module files and the two calling blocks.
- Write moved blocks so existing resources map to their new addresses
  inside the module, and nothing is destroyed.

<dev>[paste]</dev>
<prod>[paste]</prod>

Splitting the request in two is a form of prompt chaining: you correct the interface while it is cheap to change. The moved requirement in step 2 is what makes the refactor safe on existing infrastructure, as explained next.

Prompt 3: Refactor without destroying resources

Renaming a resource or moving it into a module looks harmless in a diff but, by default, Terraform plans to destroy the old address and create a new one. HashiCorp’s refactoring documentation describes the moved block, which records that an object has a new address so Terraform updates state instead of replacing the resource. It covers renames, moving into modules, and switching from count to for_each (mapping [0] to a key such as ["small"]). The same page notes that module refactoring with moved blocks requires Terraform v1.1 or later, and that removing a moved block later is a breaking change for anyone who has not applied it yet.

I am refactoring Terraform. Old and new code are below.
Write the moved blocks needed so that `terraform plan` shows zero
destroys and zero creates for existing objects.

Rules:
- One moved block per changed address, including each count index or
  for_each key that changes.
- Do not use terraform state mv commands; use moved blocks only.
- If an address change cannot be expressed with moved (for example a
  resource type change), say so explicitly and explain the options.
- Then list what I should see in the plan output if this is correct.

<old>[paste]</old>
<new>[paste]</new>
<current_state_addresses>[paste output of: terraform state list]</current_state_addresses>

Pasting terraform state list output is the key detail. It gives the model the real addresses, including indexes and keys, instead of letting it reconstruct them from code.

Prompt 4: Review a plan before apply

Plan review is where an AI assistant can save the most time, because long plans are tedious to read and the dangerous line is often buried. The plan symbols are documented in the terraform plan reference: + create, - destroy, ~ update in place, and -/+ destroy and then recreate. The same page warns that a saved plan file stores sensitive values in cleartext, so treat plan output as sensitive too. Redact before pasting any plan into an external tool, or use an approved internal deployment.

Review this Terraform plan before I apply it to [production].
The intended change was: [one sentence, e.g. "raise the ASG max size
from 4 to 6"].

<plan>
[paste text output of terraform plan, secrets redacted]
</plan>

Report, in this order:
1. Every destroy (-) and replace (-/+), with the attribute that forces
   replacement if the plan shows it.
2. Any change that is NOT explained by the intended change above.
3. Security-relevant changes: IAM policies, security group or firewall
   rules, public access settings, encryption, logging.
4. Changes to resources that hold data (databases, buckets, disks,
   queues) even if in-place.
5. A one-line verdict: "matches intent", "matches intent with
   side effects (listed)", or "does not match intent".
Quote resource addresses exactly. Do not summarize resources you were
not shown.

A worked example

This example is illustrative. Suppose the intended change was “add a cost_center tag to the logs bucket”, and the plan excerpt reads:

  # aws_s3_bucket.logs will be updated in-place
  ~ resource "aws_s3_bucket" "logs" {
      ~ tags = {
          + "cost_center" = "platform"
        }
    }

  # aws_db_instance.app must be replaced
-/+ resource "aws_db_instance" "app" {
      ~ identifier = "app-prod" -> "app-production" # forces replacement
    }

Plan: 1 to add, 1 to change, 1 to destroy.

A good review following the prompt puts aws_db_instance.app at the top under item 1, notes that the identifier change forces replacement, flags it under item 2 as unrelated to the tagging task and under item 4 as a data-holding resource, and returns “does not match intent”. The summary line “1 to add, 1 to change, 1 to destroy” is easy to skim past; the structured review is not. The fix is to revert the identifier change, which probably came from an unrelated edit or a model “tidying up” names.

Prompt 5: Debug a Terraform error

[paste <terraform_context>]

Command: terraform [init | validate | plan | apply]
<error>[full error output, including the file:line and the
"Error:" summary]</error>
<code>[the block at the reported location and anything it references]</code>

1. Classify the error: HCL syntax, type/validation, provider schema
   (unknown argument), provider API error from the cloud, state/lock,
   or dependency cycle.
2. Explain the cause with reference to the exact line.
3. Give the fix. If the error is from the cloud API (permissions,
   quota, name conflict), say which permission or limit is involved
   and do not change unrelated code.

Classification first matters because the fixes are completely different. An “Unsupported argument” error means the code does not match the provider schema (often an outdated example), while an AccessDenied during apply means the code is fine and the credentials are not.

The validation pipeline AI-written Terraform must pass

Prompts reduce errors; tools catch the rest. Run these in order, locally and in CI:

StepWhat it catchesWhat it does not catch
terraform fmt -check -recursiveFormatting drift from the canonical styleAnything semantic
terraform validateSyntax, internal consistency, argument types, unknown arguments for installed providersValues the cloud API will reject; anything requiring state
Linter (e.g. TFLint)Your own organization rules and, through plugins, some provider-specific checksIntent: whether this is the change you meant
Policy / security scannerOpen ingress, missing encryption, wildcard IAM, per your rulesRules you have not written
terraform plan -detailed-exitcodeExit code 2 signals changes, 0 none, 1 error; the full set of actions against real stateWhether the changes are wise; that needs a human
Human plan review (Prompt 4 as a helper)Unintended replaces, side effects, risky security changesNothing, if done; everything, if skipped

The style guide notes that terraform validate does not check provider-specific validity or evaluate state, and that Terraform has no built-in linter, which is why the third-party and policy steps exist. If your pipeline runs on GitHub Actions, our security checklist for AI-generated GitHub Actions workflows covers the CI side, including how cloud credentials are scoped. A secret scanner in a pre-commit hook, such as the Gitleaks setup we documented, catches keys that a model may have copied into a .tfvars example.

Mistakes AI-generated Terraform commonly contains

  • Outdated resource patterns. Arguments that moved to separate resources in newer provider versions. Fix: state your provider version range and require the # VERIFY marker.
  • Missing version constraints. No required_version or unpinned providers. The style guide recommends pinning providers in required_providers and setting a minimum CLI version.
  • Secrets as variable defaults. A default = "changeme" password, or an example .tfvars with a real-looking key. Fix: pull secrets from a secrets manager data source; consider the variable ephemeral argument, which the variables documentation says keeps a value out of state and plan files.
  • Over-broad permissions. "Action": "*" or 0.0.0.0/0 “to make it work”. Fix: put the security baseline in the context block and ask the model to list every permission it grants.
  • Renames without moved blocks. Cosmetic label changes that turn into replacements. Fix: Prompt 3, and read every -/+ in the plan.
  • count over lists of distinct things. Removing one item reindexes the rest. Fix: for_each over a map with stable keys.

The same draft-then-verify approach applies to the container layer that often sits on top of this infrastructure; see our AI prompts for Dockerfiles and container configs.

Sources

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top