October 31, 2026

AI Terraform: Write Infrastructure Code and Review the Plan

AI Terraform cover with a terminal line running terraform plan with an output file

AI Terraform help is a double-edged tool. An assistant can write a working module in a minute, explain a confusing plan and translate a console setup into code, and it can just as quickly write a security group open to the whole internet, a storage bucket without encryption or a resource argument that no longer exists. Infrastructure code differs from application code in one important way: a mistake does not only crash a page, it can delete a database, expose data or run up a bill. The assistant drafts, and the plan, the review and the human decide what happens.

This guide shows how to prompt for Terraform that you can review, which risks to look for in generated code, how to protect state and secrets, how to read a plan and which workflow keeps a mistake from reaching production. It assumes basic familiarity with Terraform, but explains the key ideas as it goes.

What AI Terraform assistance is good for

Terraform describes infrastructure as code: you write the resources you want, run a plan to see what would change and apply it. The Terraform documentation explains the language and the workflow. Assistants are good at the writing and explaining parts of this job. They can scaffold a module, turn a list of requirements into resources and variables, add tags and outputs, explain what an error means, convert a configuration from one cloud provider’s style to another and write documentation for a module.

They are weaker at the facts that change. Provider versions add and remove arguments, a model’s memory of a resource may be a year old and cloud services have limits and defaults that differ by region and account. An assistant has no access to your account, your existing state or your organisation’s policies, so it cannot know what already exists or what is allowed. Our guide to AI for DevOps covers the wider picture, and when not to trust AI-generated code explains the general rule: the more expensive a mistake is, the more checking the code needs.

Prompting for Terraform you can review

Give the assistant the context it cannot see. State the Terraform version, the provider and its version, the region, the naming convention, the tagging rules, the environments and whether the code is a root configuration or a reusable module. Describe the goal in plain words and the constraints that matter: no public access, encryption on, private networking, a cost ceiling, specific instance sizes. Then ask for specific outputs: the code, the variables with descriptions and types, the outputs and a list of assumptions.

Write Terraform (version 1.x, AWS provider pinned to a major version) for:
- one private object storage bucket for application logs
- encryption at rest on, public access fully blocked, versioning on
- lifecycle rule: move to cheaper storage after 30 days, delete after 365
- variables: name prefix, environment, tags
- outputs: bucket name and ARN
Do not use wildcard permissions. Do not hard-code account IDs.
List every assumption and anything that may cost money.

Notice what the prompt does: it forbids wildcard permissions and hard-coded values, and asks for cost notes. A short prompt like “make an S3 bucket” produces a short, insecure answer. Ask the assistant to explain each resource in one line, and to say which arguments are optional defaults. That makes your review faster and teaches you the language.

Typical mistakes in generated infrastructure code

Learn the failure patterns, because the same ones come back. The table lists the most common and a way to catch each.

Mistake Why it matters How to catch it
Open ingress such as 0.0.0.0/0 on admin ports Exposes servers to the internet Search for the range; review security rules
Wildcard permissions in policies Gives far more access than needed Look for “*” in actions and resources
Storage without encryption or public block Data exposure Security scanner and manual review
Invented or deprecated arguments Plan fails or behaves unexpectedly terraform validate and provider docs
Hard-coded secrets or account IDs Leaks and poor reuse Search for keys; use variables and a secret store
Missing lifecycle protection on data A change can destroy a database Read the plan for destroy and replace
Oversized resources Unnecessary cost Review sizes and counts against needs
Unpinned provider versions Surprise changes on the next run Pin versions in required_providers

After generation, run the standard tools before you read a line. Format with terraform fmt, check syntax and references with terraform validate, and run a linter and a security scanner that your team uses. These tools catch many invented arguments and many misconfigurations. They do not replace review, because a configuration can be valid and still wrong for your needs. For general code security habits, see AI code security review.

Reading the plan is the real review

The plan is where Terraform shows what it intends to do, and it is the most important artefact. Save it with terraform plan -out=tfplan and apply that exact file, so that what you reviewed is what runs. The documentation for the plan command describes the options. Read the summary line first: how many resources will be added, changed and destroyed. Any destroy or replace on a stateful resource, such as a database or a disk, needs a clear explanation.

You can paste the plan, with secrets and account identifiers removed, into an assistant and ask it to explain what will change in plain language, which changes are risky and which could cause downtime. This works well as a second reader. Verify its claims against the plan text, since an assistant can overlook a line or misread a nested change. Ask specifically: “List every resource that will be destroyed or replaced and the attribute that forces it.” Then compare with the plan yourself. In a team, require another person to approve production plans.

State, secrets and access

Terraform keeps a state file that maps your code to real resources, and it can contain sensitive values in plain text. The documentation on state explains why it must be protected. Use a remote backend with encryption, access control and locking, so that two people cannot apply at once, and never commit state files or variable files that hold secrets to a repository. Never paste state files into an assistant.

Secrets belong in a secret manager or in environment variables supplied by your pipeline, and marked as sensitive in the configuration. Ask the assistant to write code that reads secrets from a manager and not from literals, and to avoid outputs that print sensitive values. Apply the principle of least privilege to the credentials that Terraform itself uses: a pipeline that can create everything in every account is a large target. Use separate roles for plan and apply where you can, and separate accounts for production and testing.

Modules, environments and drift

Once you have more than a couple of resources, structure helps. Ask the assistant to propose a module layout, with a small number of well-named modules, clear inputs and outputs and no hidden global behaviour. Keep environments separate, with their own state, and use the same module code with different variable values, so that testing resembles production. Avoid clever dynamic constructs that save ten lines and cost an hour of confusion for the next reader.

Real infrastructure drifts: someone changes a setting in the console, or a service updates a default. Run plans regularly, and ask the assistant to help interpret unexpected differences, but decide yourself whether to change the code or the resource. For importing existing resources, an assistant can draft import blocks and matching configuration, which you must check against the live resource to avoid a plan that tries to replace it. Open-source alternatives and forks of Terraform exist, such as OpenTofu, and commands and syntax are largely compatible, though you should check the specifics for the tool you use.

Cost and naming checks before you apply

Cost is a quiet risk in AI Terraform work, because an assistant often chooses generous defaults: large instance sizes, multiple availability zones, provisioned throughput or extra copies of data. Ask it to list every resource that has an ongoing charge, the main factor that drives the price and a cheaper option that still meets the requirement. Then check the numbers with your provider’s own pricing calculator, since an assistant’s memory of prices is unreliable and prices change.

Also review names and tags. Consistent names make resources easy to find and to clean up, and tags tell finance and security who owns what. Ask the assistant to apply your tagging rule to every resource that supports tags and to fail loudly if a required variable is missing. Remove experimental resources when a test ends, and consider an automatic expiry tag for anything temporary, so that a forgotten test environment does not run for months.

A safe workflow for AI-assisted Terraform

A workflow with five stages keeps the risk low. First, write the request with context and constraints, and receive code and assumptions. Second, run format, validate, lint and security scans locally. Third, open a pull request, where a colleague reviews the code and the plan output in the review. Fourth, apply the saved plan from a pipeline, in a test environment first. Fifth, record what changed and why, and update the module documentation, which an assistant can draft.

Automate stages two to four in your pipeline, as shown in our guide to an AI GitHub Actions workflow, and protect production with manual approval. If something fails in production, collect logs and write the review with the help of AI incident postmortem and AI log analysis. Keep a record of the prompts that produced good modules, so that the team shares them, and delete the ones that produced trouble.

How Ask Mio helps with Terraform

Ask Mio is one assistant with five modes, and Mio routes each request to a suitable model. On the free plan, Chat and Write can explain a plan, write module documentation and draft a review checklist. The Coding plan adds Code mode and a code execution sandbox, which suits scripts and small checks, and Research mode with web search and cited sources helps you look up current provider documentation instead of trusting memory. Terraform providers change often, so always compare generated arguments with the official docs.

Memory and projects can store your naming rules, tagging policy and provider versions, so that every new chat starts with them. Mio cannot access your cloud account or your state, and it should not be given secrets. Chats and files stay yours, can be exported or deleted at any time and are not used to train models. Check the live pricing page for current plan features and limits.

Frequently Asked Questions

Is it safe to let AI write Terraform code?

It is safe as a drafting tool if you validate, lint, scan and review every change and read the saved plan before applying. It is unsafe to apply generated code directly to production. Treat the assistant like a junior colleague whose work always needs a second reader.

Should I paste my Terraform state into an assistant?

No. State files can contain secrets, identifiers and the full shape of your infrastructure. Paste only small, sanitised snippets of code or plan output, with secrets and account identifiers removed, and check your provider’s data policy before sharing anything sensitive.

Why does generated Terraform fail validation?

Common causes are invented arguments, deprecated attributes, wrong block structures and mismatched provider versions. Run terraform validate, paste the error back with the relevant code and ask for a fix, then compare the result with the provider documentation for your pinned version.

How do I review a Terraform plan with AI?

Remove secrets and identifiers, paste the plan and ask for a plain-language list of what will be created, changed, destroyed and replaced, plus the risky items. Then check each claim against the plan yourself and require a human approval before applying to production.

Which Ask Mio plan helps with infrastructure code?

The free plan includes Chat and Write for explanations and documentation. The Coding plan adds Code mode and a code execution sandbox, and paid plans add Research with cited sources, file uploads and memory. Check the live pricing page for current points and limits before choosing.

The Bottom Line

AI Terraform assistance speeds up writing modules, explaining plans and documenting changes, but infrastructure code needs more checking than ordinary code. Give the assistant full context, demand secure defaults, run format, validate and scanners, read the saved plan, protect state and secrets and require human approval for production. You can start on the free plan and compare options on the Ask Mio pricing page.


Try Ask Mio free

Free plan, no card required.

Start free