Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 128/ 160
07. Deployment

Infrastructure as Code

Terraform/Pulumi/CDK to provision GPUs, queues, and storage reproducibly.

IntermediateTerraform · Drift Control3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Infrastructure as code means describing your servers and cloud setup in files, so computers can create the same setup again and again exactly as written.

Think of it like…

Architectural blueprints and a building inspector: instead of builders improvising on site, every change is drawn, reviewed against codes (policies and budgets) and then constructed exactly as drawn, and any unauthorised modification can be spotted by comparing the building to the plans.

Where you’ve seen it

A Terraform repository defines a VPC, a managed Kubernetes cluster, a CPU node pool, a GPU node pool (2 nodes of a GPU instance), an SQS queue, an S3 bucket for documents, an RDS Postgres and IAM roles, about 40 resources, split into separate state files for network, data and compute per environment so a mistake in one stack can't touch another. A pull request that adds the GPU pool shows Plan: 3 to add, 1 to change, 0 to destroy; the CI job comments the plan, runs policy checks (only approved GPU instance types, mandatory cost-centre tags, no public buckets) and an Infracost estimate: 2 GPU nodes × $3.00 an hour × 24 × 30 = $4,320 a month. A reviewer approves, the merge applies the change with a locked remote state (S3 with state locking), and a nightly terraform plan job reports drift if someone changed a security group by hand. Rebuilding the whole staging environment from scratch takes 25 minutes versus about 3 days when it was hand-assembled. Databases have prevent_destroy, secrets are references to the secret manager (state is encrypted and access-controlled because it can contain sensitive values) and non-production GPU pools scale to zero overnight on a schedule.

Words you’ll hear

Plan / apply
Preview the diff of changes, then execute them.
State
The record of real resources managed by the tool; must be protected and locked.
Drift
Real infrastructure differing from the code, usually from manual changes.
Policy as code
Automated rules (OPA, Sentinel, Checkov) that reject non-compliant plans.

Visual diagram

Loading interactive diagram

Theory & deep dive

Core concepts and tools

Declarative IaC describes the end state; the tool computes the actions to reach it. Terraform/OpenTofu: providers (AWS, GCP, Azure, Kubernetes, Helm) expose resources; modules package reusable components (a standard VPC, a GPU node pool); terraform plan shows additions, changes and destructions; apply executes; state maps code to real resource IDs. Store state in a remote backend with locking (S3 plus a lock table, GCS, Terraform Cloud) so two applies can't collide, encrypt it and restrict access because state may contain sensitive attributes. Pulumi and AWS CDK let you use Python, TypeScript or Go with loops, functions and tests, at the cost of more power to write unreviewable code; Crossplane manages cloud resources through Kubernetes APIs.

Structure for safety: separate state and pipelines per environment and per layer (network, data, compute) so a change to GPU nodes can't destroy the database; use workspaces or directories per environment with shared modules and per-environment variables; pin provider and module versions; mark critical resources prevent_destroy or with deletion protection; reference secrets (secret manager ARNs) rather than putting values in code; and import existing resources so legacy infrastructure comes under management. Keep the code DRY but readable: small modules with clear inputs and outputs beat sprawling variable tangles.

A plan summary

Plan: 3 to add, 1 to change, 0 to destroy. Adds: GPU node group, launch template, scaling policy. Changes: cluster autoscaler IAM policy. A destroy count above zero on a database triggers an extra approval.

Key takeaway: Describe desired state, review plans, protect and lock state and split stacks to limit blast radius.

Policy, cost, drift and AI-specific practices

Policy as code (OPA/Conftest, Sentinel, Checkov, tfsec) evaluates the plan before apply: only allowed regions and GPU instance types, required tags (owner, cost centre, environment), encryption on, no public buckets or open security groups, mandatory budgets. Cost estimation (Infracost) comments the monthly delta on the PR: two GPU nodes at $3.00 an hour is 2 × 3.00 × 24 × 30 = $4,320 a month, a number reviewers should see before approving. Add budgets and alerts at the cloud account level as a backstop. Drift detection: run plan on a schedule (nightly) and alert on differences, then either revert manual changes or codify them. Test modules with tools such as Terratest and validate with terraform validate and linters in CI.

AI-specific practices: provision GPU capacity through node pools with taints and autoscaling limits (min, max), use spot instances for fault-tolerant batch work with fallbacks, schedule non-production scale-down (GPU pools to zero outside working hours), pre-create queues, dead-letter queues, buckets (versioned, encrypted) and vector stores as code, manage IAM roles with least privilege per service and keep quota requests (GPU quotas often need lead time) tracked. Package a golden path module so teams spin up a service with queue, bucket, role and alarms in one block. Document disaster recovery: the 25-minute rebuild of staging proves the code is complete, and a periodic rebuild test (or ephemeral preview environments) keeps it true.

Cost guardrail

PR adds 2 GPU nodes. Infracost: +$4,320/month, over the team's $3,000 incremental budget, so the policy requires platform-lead approval and a scale-to-zero schedule for nights and weekends, which cuts the non-production estimate by about 65%.

Key takeaway: Check policies and cost on every plan, detect drift and codify GPU pools, queues, storage and IAM as reusable modules.

How it works, step by step

Step 1 of 4
Platform

1. Choose tools and structure

Pick Terraform/OpenTofu, Pulumi or CDK; split stacks by layer and environment with remote locked state.

network · data · compute per environment
Key numbers at this step
Pin
provider versions

When to use it & trade-offs

What it is

Infrastructure as Code (IaC) defines cloud resources (networks, Kubernetes clusters, GPU node pools, queues, buckets, databases, IAM roles) in version-controlled declarative files that a tool applies to create, change or destroy real infrastructure. Terraform/OpenTofu uses HCL, Pulumi and the AWS CDK use general-purpose languages. The core workflow is plan (a diff of what will change) then apply, with a state file recording what exists. IaC brings reproducibility (rebuild an environment from the repo), review (infrastructure changes go through pull requests), drift detection (find manual changes) and policy and cost checks before anything is created.

Why it matters: AI infrastructure is expensive and easy to get wrong: a forgotten GPU node pool costs thousands a month, a public bucket leaks documents and a hand-built staging environment never matches production. Clicking through consoles doesn't scale, can't be reviewed and can't be recreated after a disaster. IaC turns infrastructure into something you can test, diff, approve and roll back, and it makes cost and security rules enforceable before resources exist.

When to reach for it

  • Provisioning GPU pools, queues, storage and clusters
  • Reproducible staging and production environments
  • Enforcing security and cost policies before deployment

When to avoid or be careful

  • A single giant state for every environment
  • Secrets as literals in code or unprotected state
  • Hand-editing resources that IaC manages

IaC tools

Terraform / OpenTofu
Best for: Multi-cloud declarative infrastructure with a large ecosystem

Strengths: Mature; readable plans; many providers.

Watch out: HCL limits; state management needed.

Pulumi or AWS CDK
Best for: Teams preferring general-purpose languages

Strengths: Loops, functions, unit tests; familiar syntax.

Watch out: Easier to write complex, hard-to-review code.

Manual console changes
Best for: One-off exploration only

Strengths: Quick to start.

Watch out: Unreviewable, unrepeatable, drifts.

Interview signals & numbers to know

When this topic comes up

  • “Who changed that security group?”
  • terraform plan
  • Drift detection
  • Policy as code
  • Infracost

Benchmarks & rules of thumb

$4,320/month -
2 GPU nodes at $3.00/hour
25 min vs 3 days -
environment rebuild from code versus by hand
+3 ~1 −0 -
plan summary format (add, change, destroy)

Common mistakes & follow-ups

Common interview mistakes

  • Applying from a laptop with no review or locking.
  • Letting a change to compute resources touch the database state.
  • Ignoring GPU quota lead times when planning capacity.

Likely interviewer follow-ups

  • How would you manage GPU infrastructure with IaC?
  • What is drift and how do you detect it?
  • Why split Terraform state?
Interview tip: Mention reviewing plans with policy and cost checks. It shows IaC is a governance tool, not just automation.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Infrastructure as Code with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Environment Configs
Next topic
Serverless Functions