cs.oldnet

All sheets / Cloud & Infra

Terraform

Infrastructure as code: workflow, state, modules and HCL syntax.

Workflow

terraform init                 # providers, backend, modules
terraform fmt -recursive; terraform validate
terraform plan -out=tfplan
terraform apply tfplan
terraform destroy
terraform plan -target=aws_s3_bucket.site   # use sparingly
terraform apply -replace=aws_instance.web   # force recreate

Core blocks

terraform {
  required_version = ">= 1.6"
  required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } }
  backend "s3" {
    bucket         = "tf-state-prod"
    key            = "web/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-locks"     # or use_lockfile = true (1.10+)
    encrypt        = true
  }
}
provider "aws" { region = var.region }

variable "region" {
  type    = string
  default = "us-east-1"
}
locals { name = "${var.app}-${terraform.workspace}" }

resource "aws_s3_bucket" "site" { bucket = local.name }
data "aws_caller_identity" "me" {}
output "bucket" { value = aws_s3_bucket.site.id }

State

  • Maps config ↔ real resources; stores attributes (may hold secrets: encrypt + restrict access).
  • Remote backend (S3 + locking) for teams; never commit state.
  • Drift: real infra changed outside TF; plan shows it, apply -refresh-only accepts it.
terraform state list
terraform state show aws_s3_bucket.site
terraform state mv old.addr new.addr     # or a moved {} block
terraform import aws_s3_bucket.site my-bucket  # or an import {} block
terraform state rm aws_s3_bucket.site    # stop managing, keep resource

Loops & conditionals

resource "aws_sqs_queue" "q" {
  for_each = toset(["orders", "emails"])     # stable keys: prefer over count
  name     = "${each.key}-queue"
}
resource "aws_eip" "ip" { count = var.enable ? 1 : 0 }

dynamic "ingress" {
  for_each = var.ports
  content {
    from_port = ingress.value
    to_port   = ingress.value
    protocol  = "tcp"
  }
}
[for s in var.subnets : s.id if s.public]
{ for k, v in var.tags : lower(k) => v }

Modules

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"
  name    = "main"
  cidr    = "10.0.0.0/16"
}
# reference outputs: module.vpc.vpc_id

Root module = where you run TF. Child modules: variables.tf, main.tf, outputs.tf. Version-pin modules.

Lifecycle & dependencies

lifecycle {
  create_before_destroy = true     # zero-downtime replace
  prevent_destroy       = true     # guard prod DBs
  ignore_changes        = [tags]   # managed elsewhere
}
depends_on = [aws_iam_role_policy.x]   # hidden dependency only

Environments

  • Separate state per env (dirs or workspaces); dirs + shared modules is most explicit.
  • Terragrunt or TF Cloud/Stacks for DRY multi-env config.
  • tfvars per env: terraform plan -var-file=prod.tfvars.

CI/CD for Terraform

  • PR: fmt -check, validate, tflint, checkov/tfsec, plan posted as PR comment.
  • Merge to main: apply the saved plan with OIDC role; require approval for prod.
  • Lock provider versions (.terraform.lock.hcl committed).

Interview Qs

  • count vs for_each: count by index (removing middle item shifts others); for_each by key.
  • Terraform vs CloudFormation: multi-cloud, HCL, state you manage vs AWS-only, AWS-managed state, drift detection built in.
  • Secrets: mark sensitive = true, pull from Secrets Manager/SSM at runtime, encrypt state.