Unit 3 / 11

Managing Infrastructure as Code: Artificial Intelligence with Terraform and IaC

Gains:

  • Ability to understand the IaC concept and Terraform's working cycle (init, plan, apply, state, module) and have artificial intelligence produce safe HCL drafts
  • Ability to check each change with a plan before applying and catch unexpected destroy/replace lines
  • Ability to apply the principles of keeping secrets out of the code, keeping state securely, and minimizing IAM permissions

In the past, setting up a server was a matter of clicking through a cloud panel: create a virtual machine, set up the network, add the security rule. This method was slow, error-prone, and unrepeatable — it was nearly impossible to set up the same environment a second time. Today, infrastructure is managed as code. IaC (Infrastructure as Code) is an approach to describe cloud resources such as servers, networks, and databases in text files rather than manually. These files sit in version control (Git); You can see who changed what, when, and what; You can set up the same infrastructure many times, in exactly the same way, with one command.

The most common IaC tool is Terraform. Terraform takes the definitions you write in a readable language called HCL (HashiCorp Configuration Language — Terraform's configuration language), translates them into the cloud provider's (AWS, Azure, GCP) API and creates the resources. The AI ​​knows HCL very well and produces complex blocks quickly. But in IaC, the cost of a mistake is high: one wrong definition can wipe out an entire production database. That's why the golden rule in Terraform is to see every change with a 'plan' before implementing it.

Terraform's runtime

Terraform works with three basic commands — knowing these is a prerequisite for controlling AI output:

  • `terraform init`: Starts the project, downloads the necessary provider plugins.
  • `terraform plan`: Compares the current situation with the desired situation and shows what to add, what to change, what to delete. Doesn't implement anything. It is the most critical security step.
  • `terraform apply`: Actually applies the Plan, creating/modifying resources.

Additionally, two concepts are vital. State (state file): This is the file where Terraform keeps the current state of the resources it manages; It is usually stored in a remote and locked warehouse so that two people cannot change or destroy it at the same time. Module: Reusable configuration package; For example, you can use the "set up a network" module in many projects.

Tip: The most dangerous sign in a Terraform output is destroy or -/+ (replace) lines in the plan output. These mean that the resource will be deleted. If you see an unexpected destroy in a plan, never apply, first understand why it appeared.

Step by step: Writing IaC with AI

  1. Clarify the desired infrastructure. Be concrete like "one VPC, two subnets, one security group and one t3.micro EC2 on eu-central-1".
  2. Specify provider and version. Which cloud, which Terraform and provider version? If you don't specify a version, AI may return outdated/incompatible syntax.
  3. Have the HCL draft produced. Also request variables and outputs.
  4. Take Secret out. Values ​​such as passwords and keys should go to the variable and secret vault, not to the code.
  5. Run `init` + `plan`. Read the plan output line by line; Check for unexpected deletions.
  6. Start small, implement gradually. Apply it in an isolated test account/environment first.

Security: IaC-specific risks

IaC is as risky as it is powerful. Three critical points:

  1. There is a secret in the state file. Terraform state sometimes keeps sensitive values, such as database passwords, in plaintext. Never put State in a public repository; Use an encrypted, restricted-access remote backend.
  2. Do not embed secrets in HCL. Lines like password="prod123" are permanently written to Git history. Instead, use a variable and give the value at runtime from the environment variable (TF_VAR_...) or secret vault.
  3. Very broad IAM permission. AI sometimes produces blocks like Action: "*" (allow everything) to "make it work". This is a vulnerability; narrow the permission to the minimum required.
Attention: Once a secret enters Git history, it remains in the past and can be compromised, even if you delete the file. If you commit by mistake, immediately cancel and rotate the secret; Just deleting is not enough.

Risky plan signs table

Plan printout

Meaning

what to do

+create

New resource will be added

Generally safe, review though

~ update in-place

The source will change on site

Verify impact (will there be an outage?)

-/+ replace

Will be deleted and recreated

CAUTION: data loss may occur

- destroy

The resource will be destroyed

STOP: never apply if you're not expecting it

three mini cases

Case 1 — 2 days' work in 3 hours. One team was going to write Terraform to set up a new test environment (VPC, subnets, RDS database, ECS cluster) but they had just moved to HCL. They described the architecture and versions to the AI ​​and produced a modular blueprint. They verified each module with the plan and had it up and running in 3 hours; It would take them two days of manual trial and error.

Case 2 — the plan caught a deletion. An engineer ran a plan without applying an AI-generated update code. The output contained -/+ replace for the production database — the AI ​​attempted to replace a non-replaceable field, which meant deleting and recreating the database. The engineer stopped apply and changed the change to the safe method. The habit of planning prevented a disaster.

Case 3 — buried secret leak. A junior, YZ issued db_password = "S3cret!" He committed the line as is and pushed it. Caught in code review; The password was immediately canceled and changed, the value was moved to a variable and fed from the secret vault. Lesson: There are never plaintext secrets in HCL.

Four copyable templates

1) Generating infrastructure draft:

Write the following infrastructure on [CLOUD: AWS] with Terraform (version ~> 1.7): [SOURCE LIST]. Region [X]. Rules:- Make all sensitive values ​​variable, don't embed them in HCL.- Fix provider version (required_providers).- Minimize IAM permissions, don't use "*".- Return [X, Y] as output. Give code modularly and with explanations.

2) Interpreting the plan output:

Analyze the 'terraform plan' output below. List me:(1) what resources were added/changed/DELETED,(2) rows at risk of data loss or interruption,(3) 3 questions I should ask before applying.Plan: [OUTPUT]

3) Examine existing HCL for security:

Check the following Terraform code for security: embedded secret, overly broad IAM permission, open network rule (0.0.0.0/0), unencrypted storage? Write each finding in order of importance and correction. Code: [HCL]

4) Convert the repetitive code to the module:

Convert the following repetitive Terraform code into a reusable module: what values should be variables, what should the module interface be? Also show example usage. Code: [HCL]

Weak prompt / Strong prompt

Weak: "Create a database with Terraform."

Result: unclear which cloud, which engine, which version, encrypted or not; With legacy syntax, AI can provide a publicly available example that embeds the password into the code.

Strong: "Create an RDS PostgreSQL 15 instance on AWS with Terraform ~> 1.7. Make the password variable, don't embed it in the code. Storage is encrypted, accessible only from private subnet, not public. Fix provider version. Return endpoint as output."

Difference: the second prompt gives the engine, version, encryption, network constraint and secret rule — the output is secure and close to prod.

Common mistakes

  • To `apply` without making a `plan`. The most expensive mistake in IaC; always plan first.
  • Embedding Secret in HCL. Creates permanent leakage into Git history.
  • Storing State insecure. An unencrypted, unlocked, public state is a disaster.
  • Not fixing the version. Using provider without specifying a version will lead to sudden failures in the future.
  • *`Action: Broad permission such as ""`.** Violates the principle of least privilege.
  • Ignoring unexpected `destroy`. Applying the delete lines in the Plan without questioning.

In summary

IaC turns infrastructure into repeatable, versionable, and auditable code; The most common tool is Terraform. AI quickly produces HCL stubs, but you must provide the version, cloud-specific details, and security rules. The infallible rule in Terraform: to see every change with a plan, to query unexpected deletions, to keep secrets away from the code and to keep the state securely. The destroy and replace lines in a plan output are the places that should be read most carefully.

Application task

Have the AI generate a small infrastructure (e.g. a storage bucket and an access policy) using the "Generate infrastructure sketch" template above. Then: (1) have the "vetting" template check for secret or * permissions embedded in the code; (2) if possible, run init + plan in a test account and read the plan output with the "plan interpretation" template; (3) note any unexpected deletions/changes.

checklist

  • [ ] I added cloud, Terraform/provider version, and encryption/network constraints to my prompt.
  • [ ] There is no plaintext secret in the code; precision values ​​variable.
  • [ ] I narrowed down IAM/permissions to minimal permissions, * I didn't use it.
  • [ ] I ran plan before apply and read the output line by line.
  • [ ] I verified that there is no unexpected destroy/replacement in the Plan.
  • [ ] I am sure that the state is kept in an encrypted, locked and restricted backend.