Gains:
- Ability to produce IaC (Terraform, Ansible) code with artificial intelligence with the narrowest permissions and safe defaults and understand the declarative approach
- Ability to prevent data loss by reading and capturing delete and force replacement lines before applying the plan/check output
- Ability to prevent secret leakage by keeping the state file encrypted, locked, in the remote backend and breaking changes into small, reversible steps
Management of Infrastructure as Code (IaC): Terraform, Ansible and Plan Control with AI
In the past, setting up a server was done with manual clicks, commands, and personal notes; The result was irreproducible "snowflake" servers that no one knew exactly how to set up. Infrastructure as Code (IaC) is the approach that ends this chaos: servers, networks, security rules are defined not by hand, but by versionable text files (code). When you run this code, the infrastructure is set up exactly as you wrote it — the same, documented, and repeatable every time. The most common tools are Terraform and CloudFormation for cloud infrastructure and Ansible for server configuration. Here the AI is very skilled at writing, explaining and reviewing this IaC code. But the power of IaC is also its danger: one wrong line can wipe out an entire infrastructure; so the AI writes code, you read the "plan", approve it and execute it.
In this unit, we will discuss the declarative approach, the plan/apply distinction, state security and idempotency; You will learn IaC generation with AI and the most critical skill, "plan control".
Thinking declaratively: "what if", not "how to do"
Most IaC tools are declarative: you describe the final state of the system ("let's say 3 web servers, 1 load balancer"), the tool itself calculates how to get to that state. This is different from writing a script ("do this, then do that" step by step). The big advantage of the declarative approach is idempotency: even if you run the code ten times, the result is the same, because the tool checks to see if the desired state already exists, and if it does, it does not touch it. Remember this difference when you write IaC to the AI: you make it say "let this infrastructure state", not "run these commands".
Plan/apply: most vital safety railing
The life-saving feature of IaC is the plan step. In Terraform, terraform plan, in Ansible, --check mode produces a preview of "what will change if I apply it" before running the code: "2 resources will be added, 1 will change, 0 will be deleted". This is the only way to compare your intention with reality before implementation. Critical rule: never apply without reading the plan. Look especially for the "destroy" lines; If you see "12 will be deleted" instead of "1 will be changed" because of a typo, the plan has saved you from disaster. After printing the code to the AI, have it say "examine the plan output line by line with me, mark every line that contains deletion/recreation."
Caution: Some changes to Terraform "destroy and recreate" a resource rather than "updating in place". This means data loss for a database. Ignoring -/+ or "forces replacement" in the plan output is one of the most expensive mistakes.
State file: record of secrets and truth
Tools like Terraform keep the current state of the infrastructure they manage in a state file. This file is critical for two reasons. First, it may contain secrets (database passwords, keys may fall into state in plaintext); Therefore, never paste the state into a public repository or AI, keep it in an encrypted and access-restricted remote backend. Second, if the state is corrupted or lost, the vehicle loses the link between the real infrastructure and the imagined infrastructure; Therefore, a backup of the state and a lock mechanism (lock that prevents two people from breaking it at the same time) are essential.
Step by step: Secure IaC with AI
- State intent and provider. “2 servers on AWS, with Terraform, in this region, this size, and a security group.” If the cloud, tool, and version are clear, the AI produces correct syntax.
- Request security defaults. "Open security group, enable encryption, extract secrets to variable, grant public access." AI can generate loose samples by default.
- Read and understand the code. Understand every resource, every permission, line by line. Don't apply a permission you don't understand.
- Get a plan and audit it. Run plan/--check, examine the output with AI, mark the delete and rebuild lines.
- Apply small and reversible. Implement a big change in small pieces, not all at once. Know the way back at every step.
- Protect State. Use remote, encrypted backend and lock; Never leak state.
three mini cases
Case 1 — The plan recovered a database. An engineer wanted to increase the size of a database with the Terraform code he produced with AI. While he was expecting "1 to change" in the terraform plan output, he saw "1 to destroy, 1 to add" — the parameter he chose was triggering a rebuild, not an in-place update, meaning all data would be deleted. Plan control stopped irreversible data loss before it was implemented.
Case 2 — Return from loose default. A team asked the AI for a firewall code. To run the example, the AI generated a simple rule of 0.0.0.0/0, meaning "public on the internet". The engineer noticed this while reading the code and narrowed the access to only the enterprise IP range. If it were implemented without being audited, the database would be open to the entire internet.
Case 3 — State leak prevented. A junior member was about to paste the terraform.tfstate file intact into a public tool to solve a Terraform issue. Senior engineer stopped: state contained a plaintext database password. Instead, a decrypted summary describing the problem was shared and the state was moved to the remote encrypted backend.
Four copyable templates
1) IaC resource generation (secure default):
Your role: senior cloud infrastructure engineer. [Cloud, e.g. AWS] for[tool, e.g. Terraform] generate code. Purpose: [purpose].Security rules: public (0.0.0.0/0) access OPEN;start with narrowest permission; turn on encryption; extract secrets into variables,don't embed them in code; Check settings that may lead to deletion/recreation. Explain each source with a brief comment.
2) Plan output audit:
Below is a [Terraform plan / Ansible check] output. Tell me: (1) how many resources will be added/changed/deleted, (2) also mark the "destroy" or "forces replacement" lines that pose a risk of data loss, (3) list any changes that seem unexpected or dangerous. Output: [plan]
3) IaC code security review:
Examine the following IaC code for security: (1) are there overly broad access/permissions, (2) is encryption turned off, (3) are there secrets embedded in the code, (4) are there publicly available resources? Suggest correction for each finding. Code: [masked code]
4) Split the change into safe parts:
I don't want to implement this big infrastructure change [explanation] all at once. Break it down into small, independent steps that are easy to get back to. For each step: what changes, what should I pay attention to in the plan, how do I undo it if there are problems?
Weak prompt / Strong prompt
Weak prompt:
Write Terraform code that creates a server on AWS.
Region, size, security, network, encryption are unclear. The AI produces the loosest, most explicit defaults to work — if put into production, it would be a vulnerability.
Powerful prompt:
Your role: senior cloud infrastructure engineer. Define a web server with Terraform on AWS eu-central-1: t3.small, only from the corporate IP range (I will give it with a variable), port 443 is open, disk is encrypted, no public access, labels are mandatory. Secrets are revealed to the variable. After the code: Before implementing it, tell me the 3 line types I should pay attention to in the plan and explain the return path.
Stage
Risk
safety railing
writing code
Loose default (public)
Narrowest permission + read
plan/check
Deleting without realizing it
Plan inspection, destroy marking
Apply
Major one-time change
Small, reversible steps
state administration
Glaze leakage, distortion
Remote encrypted backend + lock
Common mistakes
- Applying without reading the plan. The plan foreshadows deletion and reconstruction; If it is skipped, data loss is inevitable.
- Not noticing the loose default. AI instances frequently produce 0.0.0.0/0; If it is moved to production, it means open source to the entire internet.
- Leaking State. Exporting the state file to the AI or open repository exposes plaintext secrets.
- Embedding secrets in code. Writing the password into IaC code is a persistent leak in the code version history.
- Mistaking a rebuild for an update. Ignoring the forces replacement line will result in data loss in databases.
Tip: Even when giving the plan output to an AI to review, base the final decision on your own knowledge, not the plan text. AI summarizes the plan and flags risky lines; but the answer to the question "is this deletion acceptable" depends on your business context.
In summary
IaC brings repeatability and documentation by managing infrastructure with versionable code rather than manual clicks. AI is a powerful partner in writing this code, describing it, and reviewing it for security. But the power of IaC is its danger: one line can wipe out the entire infrastructure. Think declarative, start with the narrowest permission, fix loose defaults, keep secrets out of code and state. The most vital guardrail is the plan/check step: never execute without reading the delete and rebuild lines. Keep State encrypted, locked, and remote. The code is AI's, the decision is yours.
Application task
Choose a small infrastructure target (for example, a single virtual machine and a security rule). With the "IaC resource generation" template above, ask the AI for a code with safe defaults. Double-check the code with the "IaC code security review" template and try to find at least one loose setting. If possible, run plan/--check on a test account and review the output with the "Plan output check" template; See if there is a delete or recreate line. Write down your findings and how you will secure the state in 6 points.
checklist
- [ ] Did I specify cloud, tool and version to AI and request code with the narrowest permissions?
- [ ] Have I checked the code for loose defaults (0.0.0.0/0, closed encryption)?
- [ ] Have I extracted the secrets to the variable instead of embedding them in the code?
- [ ] Did I read the plan/check output and mark the delete lines before applying?
- [ ] Have I evaluated the data loss impact of "forces replacement" / rebuild lines?
- Didn't I keep the [ ] State file encrypted, locked, in the remote backend and leaked it out?