lesson

Terraform & IaC

Terraform workflow, state management, modules, and best practices.

Terraform & Infrastructure as Code

Terraform Workflow

terraform init    → download providers & modules
terraform plan    → preview changes (dry run)
terraform apply   → create/update resources
terraform destroy → tear down everything

State

Terraform tracks the real-world state of your infrastructure in a state file.

  • Local state: terraform.tfstate (default, not for teams)
  • Remote state: S3 + DynamoDB lock (AWS) or GCS + Cloud Storage (GCP)
  • terraform {
      backend "s3" {
        bucket         = "my-tf-state"
        key            = "prod/terraform.tfstate"
        region         = "eu-central-1"
        dynamodb_table = "tf-locks"
        encrypt        = true
      }
    }

    Modules

    Reusable infrastructure components:

    module "vpc" {
      source  = "terraform-aws-modules/vpc/aws"
      version = "5.0.0"

    name = "prod-vpc" cidr = "10.0.0.0/16" azs = ["eu-central-1a", "eu-central-1b"] }

    Best Practices

  • Never edit state manually — use terraform state mv/rm
  • Use remote state with locking for teams
  • Pin provider versions to avoid breaking changes
  • Use modules for repeated patterns (VPC, EKS cluster, RDS)
  • Separate environments with workspaces or directory structure
  • Plan before apply — always review the diff
  • Sign in to use the AI study buddy on this lesson.

    Resources