Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Infrastructure provisioning with Terraform

Terraform is an infrastructure-as-code tool engineers use to declare, plan and apply cloud infrastructure (resources, modules, state and backends) in a repeatable, versioned way.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Terraform is used by cloud engineers to declare and provision infrastructure (networks, servers, managed services) as code so setups are repeatable, reviewable and automatable. In AWS projects an engineer uses Terraform to create VPCs, EC2, IAM, RDS, and other services reliably, and to manage lifecycle changes without manual console steps.

Key ideas

Start with definitions (each bolded term is defined where first used):

  • Terraform: a tool for infrastructure as code (IaC) that reads configuration files and performs API calls to cloud providers to create, update, or delete resources. Exact statement: "Terraform reads HCL configuration, computes a dependency graph, produces an action plan, and executes provider API calls to converge real infrastructure to desired state." Assumption: the user has valid provider credentials available.

  • Infrastructure as Code (IaC): the practice of writing machine-readable files that declare desired infrastructure, so creation and changes are automated and version-controlled.

  • Provider: a plugin that implements API interactions for a platform (example: AWS provider implements calls to AWS services). Definition: "A provider maps Terraform resource types to provider API calls." Assumption: provider plugin installed via terraform init. Best practice: declare required_providers with version constraints in a terraform block to pin provider versions for reproducibility.

  • Resource: a declaration of a real-world object (example: an EC2 instance). Exact exam-style definition: "A resource block declares the desired state of one or more cloud objects; Terraform creates or updates API objects to match the block's attributes." Draw: for a resource block draw a small rectangle labelled resource, with arrows to cloud API.

  • Data source: a read-only query that fetches information (e.g., the latest AMI) from a provider for use in configuration. Definition: "A data block reads remote objects without managing them; use data sources to avoid hard-coded IDs."

  • Module: a collection of Terraform configuration files packaged together (a module can be local or remote). Definition: "A module is a reusable unit of configuration with inputs (variables) and outputs; using modules improves DRY (don't repeat yourself)."

  • State: the local or remote file (by default terraform.tfstate) where Terraform records the current known real-world IDs and attributes of resources. Law-like statement: "Terraform uses state to map declared resources to remote objects and to compute diffs." Assumption: if state is lost, Terraform cannot reliably make non-destructive changes.

  • Backend: where state is stored and how operations like locking are handled (examples: local, s3, remote). Definition: "The backend configures how and where Terraform state is loaded and stored." Important detail: for team use, a remote backend with locking is recommended.

  • Plan: the computed set of changes Terraform will perform. Exact: "terraform plan compares current config + state to compute create/update/delete actions without making changes." Then apply executes. By default, terraform plan refreshes state from real infrastructure unless -refresh=false is set; use terraform plan -refresh-only to detect drift without proposing resource changes.

  • Apply: the execution phase where provider API calls run to bring real resources to the planned state.

  • Workspace: named instances of state within a directory (default workspace name is "default"). Use: light-weight switching between environments, but do not treat workspaces as a full environment replacement for separate state backends.

  • Variable and Output: variable is an input to a module; output exposes values (like resource IDs) to the caller. Definition: "Variables parameterize modules; outputs let modules return computed values." Assumption: sensitive values should not be printed in outputs unless marked sensitive. Note: Sensitive values are still recorded in state; protect state (use a remote backend with encryption and access controls).

  • Lifecycle meta-argument: a block inside a resource that affects deletion/creation behaviour, e.g., prevent_destroy, create_before_destroy and ignore_changes.

  • Provisioner: code that runs on a resource (like remote-exec or local-exec) after creation. Rule: use provisioners only as a last resort; prefer provider-native or configuration-management solutions.

Dependency and graph formation (exam derivation):

  1. Terraform parses configuration and creates nodes for every resource, data, module and provider.
  2. Edges are created when one node references another (e.g., aws_instance.web.subnet_id = aws_subnet.app.id). This is a directed edge from instance -> subnet.
  3. Topological sort of graph yields safe ordering for create/update/delete.

Draw for an exam: draw three boxes left-to-right: local machine (Terraform CLI), remote backend (S3 bucket + DynamoDB lock), AWS account (show VPC, Subnet, EC2). Label arrows: "terraform init" to backend, "terraform apply" to AWS APIs, and a small file icon labeled terraform.tfstate inside backend.

Exact behaviour to remember (law-like): "Terraform never changes resources it does not own in state; to manage existing resource it must import it into state (terraform import)."

Formulas

terraform init — prepares working directory, downloads provider plugins and sets backend terraform validate — checks configuration for syntax and basic errors terraform fmt — rewrites files to canonical format terraform plan -out=plan.tfplan — computes execution plan and writes it to a file terraform plan -refresh-only — refreshes state from real infrastructure and shows drift without proposing resource changes terraform apply "plan.tfplan" — applies a saved plan file terraform apply — interactive apply after computing plan terraform destroy — removes all resources in current state terraform state list — list resources in state terraform output — print output values from state terraform import <address> <id> — import existing resource into state resource "<TYPE>" "<NAME>" { ... } — syntax to declare a resource module "<NAME>" { source = "<path-or-ref>" ... } — syntax for using a module variable "<NAME>" { type = <TYPE> default = <VAL> } — syntax to define variable output "<NAME>" { value = <EXPR> } — syntax to define output backend "s3" { bucket = "<bucket>" key = "<path>" region = "<region>" } — backend config pattern provider "aws" { region = "<region>" } — provider block depends_on = [ <address>, ... ] — explicit dependency declaration

For each above: <TYPE> means provider resource type (like aws_instance), <NAME> is resource local name, <EXPR> is HCL expression. Use SI units only when numeric values apply (not common here).

Worked examples

Example 1 — Minimal EC2 and Security Group (step-by-step): Files: main.tf with these contents (showing content — every double quote is literal):

provider "aws" { region = "ap-south-1" }

resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Allow SSH and HTTP"
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "web" {
  ami           = "ami-00000000" # replace with valid AMI ID
  instance_type = "t3.micro"
  vpc_security_group_ids = [aws_security_group.web_sg.id]
  tags = { Name = "web-server" }
}

output "instance_id" { value = aws_instance.web.id }

Commands and steps:

  1. terraform init — installs AWS provider.
  2. terraform plan -out=plan.tfplan — inspect planned actions: it will show creation of 2 resources (SG and EC2).
  3. terraform apply "plan.tfplan" — applies. After success, terraform state show aws_instance.web prints instance attributes. Expected final output: an EC2 instance created with the security group and output printed instance_id. If your AWS account has no default VPC/subnets in ap-south-1, add vpc_id to aws_security_group and subnet_id to aws_instance (or create a VPC and subnet first). (Replace AMI ID with a valid region-specific AMI. Runner must ensure proper IAM permissions.)

Example 2 — Remote state with S3 and DynamoDB locking, using a module (trace): Files: backend.tf with:

terraform {
  backend "s3" {
    bucket = "my-terraform-state-bucket"
    key    = "proj/terraform.tfstate"
    region = "ap-south-1"
    dynamodb_table = "tf-lock-table"
  }
}

Steps:

  1. Create S3 bucket and DynamoDB lock table manually (or with separate Terraform stack). Enable S3 bucket versioning and default encryption; create the DynamoDB table with a partition key named "LockID" (string).
  2. Run terraform init — Terraform asks to migrate existing local state to S3; accept if needed.
  3. Run terraform plan then terraform apply — state is stored remotely; multiple engineers will have state locking via DynamoDB. Trace note: after init, the state is read from the S3 object; while apply runs, Terraform acquires a lock record in DynamoDB. If locking fails, apply aborts to avoid race conditions.

Worked example answer style: list each command, expected messages, and the final state location s3://my-terraform-state-bucket/proj/terraform.tfstate and DynamoDB item for lock.

Common mistakes

  • Committing terraform.tfstate with secrets to version control instead of using remote backend.
  • Using count when for_each with maps/sets is more appropriate (or vice versa), causing confusing indices.
  • Expecting terraform apply to change resources when configuration hasn’t changed; instead check drift vs state.
  • Not importing existing resources before changing them (terraform import required).
  • Relying on workspaces for separate production/state isolation; incorrectly mixing workspaces with shared S3 backend keys.
  • Using provisioners for configuration management instead of cloud-init or configuration management tools.
  • Hard-coding region-specific AMI IDs in templates without using data sources or variables.

For your exam

Typical question types:

  • Definitions and short notes: define Terraform, backend, state, provider, module. Full-marks: concise definition + one sentence on use and one example.
  • Derivation/flow: explain how Terraform builds a dependency graph and orders operations. Full-marks: show steps parsing -> graph nodes -> edges from references -> topological sort -> plan -> apply.
  • Configuration writing: write main.tf to create a VPC, subnet and an EC2 instance with a variable for instance type. Full-marks: valid HCL, provider block, variable block, resources with references, an output, and correct syntax.
  • Debug/state questions: how to recover after state loss or how to import a resource. Full-marks: mention terraform import, safe backup of state, remote backend recommendation, steps to recover.
  • Diagram question: draw how local CLI, remote backend (S3 + DynamoDB lock) and AWS interact. Full-marks: show arrows for init, plan, apply, and state storage location and lock mechanism.

Always list assumptions (credentials available, correct IAM permissions) and mention security best-practices (no secrets in code, use encryption in S3).

Quick check

  1. What command downloads provider plugins and configures the backend?
  2. What file stores Terraform state by default for a local backend?
  3. Which Terraform command computes but does not execute the changes?

Answers: terraform init, terraform.tfstate, terraform plan.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?