Skip to content

Terraform — Commands & Recipes

Core Workflow

# Initialize (download providers)
terraform init

# Preview changes
terraform plan -out=plan.tfplan

# Apply changes
terraform apply plan.tfplan

# Destroy all resources
terraform destroy

# Format and validate
terraform fmt -recursive
terraform validate

State Management

# List resources in state
terraform state list

# Show specific resource
terraform state show aws_instance.web

# Move resource (rename)
terraform state mv aws_instance.old aws_instance.new

# Remove from state (without destroying)
terraform state rm aws_instance.orphan

# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0

# Force unlock (emergency)
terraform force-unlock <LOCK_ID>

Module Pattern

# modules/vpc/main.tf
variable "cidr" {
  type    = string
  default = "10.0.0.0/16"
}

resource "aws_vpc" "main" {
  cidr_block           = var.cidr
  enable_dns_hostnames = true
  tags = { Name = var.name }
}

output "vpc_id" {
  value = aws_vpc.main.id
}

# Root module usage
module "vpc" {
  source = "./modules/vpc"
  cidr   = "10.0.0.0/16"
  name   = "production"
}

Remote Backend (S3)

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "production/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Workspaces

terraform workspace new staging
terraform workspace select staging
terraform workspace list

Sources