Workspace #

Terraform workspace memungkinkan satu direktori konfigurasi mengelola beberapa state yang terpisah. Alih-alih duplikasi direktori untuk setiap environment, kamu tetap di satu tempat dan berpindah “slot” state dengan perintah sederhana. Ini terdengar elegan, dan untuk kasus penggunaan tertentu memang begitu — tapi ada trade-off yang perlu dipahami sebelum memutuskan workspace adalah solusi yang tepat untuk multi-environment kamu.

flowchart TD
    A["terraform\nworkspace"] --> B["default"]
    A --> C["dev"]
    A --> D["staging"]
    A --> E["production"]

    B --> F["state: default.tfstate"]
    C --> G["state: dev.tfstate"]
    D --> H["state: staging.tfstate"]
    E --> I["state: production.tfstate"]

    style A fill:#3b82f6,stroke:#1e40af,color:#fff
    style B fill:#6b7280,stroke:#4b5563,color:#fff
    style C fill:#10b981,stroke:#059669,color:#fff
    style D fill:#f59e0b,stroke:#d97706,color:#fff
    style E fill:#ef4444,stroke:#dc2626,color:#fff

Cara Workspace Bekerja #

Secara default, Terraform bekerja di workspace bernama default. Ketika kamu membuat workspace baru, Terraform membuat state file yang terpisah untuk workspace tersebut — tapi semua workspace menggunakan konfigurasi .tf yang sama.

STRUKTUR STATE DENGAN WORKSPACE (S3 backend):

s3://my-terraform-state/
  ├── terraform.tfstate                   ← workspace "default"
  └── env:/
      ├── dev/
      │   └── terraform.tfstate           ← workspace "dev"
      ├── staging/
      │   └── terraform.tfstate           ← workspace "staging"
      └── production/
          └── terraform.tfstate           ← workspace "production"

Semua workspace menggunakan konfigurasi .tf yang SAMA.
Yang berbeda hanyalah state file-nya.

Perintah Dasar Workspace #

# Lihat semua workspace dan workspace aktif (ditandai *)
terraform workspace list
# Output:
#   default
# * dev          ← workspace aktif saat ini

# Buat workspace baru
terraform workspace new staging
terraform workspace new production

# Pindah ke workspace lain
terraform workspace select production

# Tampilkan workspace aktif
terraform workspace show
# Output: production

# Hapus workspace (harus dalam keadaan kosong / no resources)
terraform workspace delete dev

Menggunakan terraform.workspace dalam Konfigurasi #

Nilai workspace aktif bisa diakses dalam konfigurasi melalui terraform.workspace. Ini yang memungkinkan satu konfigurasi berperilaku berbeda di setiap workspace.

# Menggunakan terraform.workspace langsung
resource "aws_instance" "web" {
  # Ukuran instance berbeda per workspace
  instance_type = terraform.workspace == "production" ? "t3.medium" : "t3.micro"

  tags = {
    Name        = "web-${terraform.workspace}"
    Environment = terraform.workspace
  }
}
# Pola yang lebih rapi: lookup map berdasarkan workspace
locals {
  # Konfigurasi per workspace dalam satu tempat
  workspace_config = {
    dev = {
      instance_type        = "t3.micro"
      instance_count       = 1
      db_instance_class    = "db.t3.micro"
      db_multi_az          = false
      db_backup_retention  = 0
      deletion_protection  = false
    }
    staging = {
      instance_type        = "t3.small"
      instance_count       = 2
      db_instance_class    = "db.t3.small"
      db_multi_az          = false
      db_backup_retention  = 7
      deletion_protection  = false
    }
    production = {
      instance_type        = "t3.medium"
      instance_count       = 3
      db_instance_class    = "db.r5.large"
      db_multi_az          = true
      db_backup_retention  = 30
      deletion_protection  = true
    }
  }

  # Ambil konfigurasi untuk workspace aktif
  config = local.workspace_config[terraform.workspace]
}

resource "aws_instance" "web" {
  count         = local.config.instance_count
  instance_type = local.config.instance_type

  tags = {
    Name        = "web-${terraform.workspace}-${count.index + 1}"
    Environment = terraform.workspace
  }
}

resource "aws_db_instance" "main" {
  instance_class    = local.config.db_instance_class
  multi_az          = local.config.db_multi_az
  backup_retention_period = local.config.db_backup_retention
  deletion_protection     = local.config.deletion_protection
}
flowchart LR
    A["Same Code\nWorkspace A"] -->|"terraform apply"| B["State A\nResources A"]
    A -->|"terraform apply"| C["State B\nResources B"]

    style A fill:#3b82f6,stroke:#1e40af,color:#fff
    style B fill:#10b981,stroke:#059669,color:#fff
    style C fill:#f59e0b,stroke:#d97706,color:#fff

Keterbatasan Workspace #

Workspace terdengar seperti solusi yang sempurna, tapi ada keterbatasan yang perlu dipahami.

KETERBATASAN WORKSPACE:

1. SATU BACKEND UNTUK SEMUA WORKSPACE
   Semua workspace di direktori yang sama menggunakan
   backend yang sama (S3 bucket yang sama, region yang sama).
   Tidak bisa pakai AWS account berbeda per workspace.
   → Tidak ideal untuk multi-account strategy

2. KONFIGURASI HARUS BISA MENANGANI SEMUA WORKSPACE
   Satu file .tf harus valid untuk semua workspace.
   Jika production butuh resource yang tidak ada di dev,
   kamu perlu conditional logic yang bisa rumit.
   → Konfigurasi bisa menjadi penuh dengan kondisional

3. MUDAH LUPA WORKSPACE AKTIF
   Tidak ada mekanisme visual yang jelas tentang
   workspace mana yang aktif.
   terraform apply di workspace production saat kamu
   pikir ada di dev → disaster.

4. TIDAK BISA BEDA PROVIDER CONFIG
   Semua workspace menggunakan konfigurasi provider yang sama.
   Tidak bisa pakai region berbeda atau assume_role berbeda
   per workspace tanpa workaround.

5. TIDAK ADA ISOLATION AKSES
   Siapapun yang bisa akses direktori bisa apply ke workspace apapun.
   Tidak ada IAM-level control per workspace.

Kapan Workspace Tepat Digunakan #

WORKSPACE TEPAT UNTUK:
  ✓ Ephemeral environment — per-PR, per-feature, per-developer
    (dibuat dan dihapus sering, tidak butuh isolasi ketat)
  ✓ Environment yang sangat mirip secara teknis
    (sama provider, sama region, sama account)
  ✓ Tim kecil dengan tingkat kepercayaan tinggi
  ✓ Proof-of-concept atau eksperimen yang ingin quick setup

WORKSPACE TIDAK TEPAT UNTUK:
  ✗ Production yang butuh AWS account terpisah
  ✗ Environment dengan konfigurasi yang sangat berbeda
  ✗ Tim besar dengan akses yang perlu dikontrol per-environment
  ✗ Kasus di mana isolasi penuh adalah kebutuhan compliance

Workflow Workspace yang Aman #

Karena workspace mudah terlupa, ada beberapa kebiasaan yang membantu mencegah kesalahan.

# KEBIASAAN BAIK: Selalu cek workspace sebelum apply

# Tampilkan workspace aktif di prompt shell (tambahkan ke .bashrc/.zshrc)
# Contoh untuk zsh dengan oh-my-zsh — tambahkan workspace ke prompt
parse_tf_workspace() {
  if [ -d .terraform ]; then
    workspace=$(terraform workspace show 2>/dev/null)
    echo " [tf:$workspace]"
  fi
}
RPROMPT='$(parse_tf_workspace)'

# Atau: gunakan alias yang selalu tampilkan workspace dulu
alias tfplan='echo "Workspace: $(terraform workspace show)" && terraform plan'
alias tfapply='echo "Workspace: $(terraform workspace show)" && read -p "Lanjutkan? [yes/no]: " confirm && [ "$confirm" = "yes" ] && terraform apply'
# Contoh workflow per-PR environment dengan workspace:

# Buat workspace untuk PR #123
terraform workspace new pr-123
terraform workspace select pr-123

# Deploy environment untuk PR ini
terraform apply -var="environment=pr-123" -auto-approve

# Setelah PR merged, hapus environment
terraform destroy -auto-approve
terraform workspace select default
terraform workspace delete pr-123


Workspace vs Directory-Based: Decision Matrix #

KRITERIA PEMILIHAN:

                          Workspace    Directory
Jumlah environment        < 4          >= 4
Perbedaan konfigurasi     Kecil        Besar
Tim yang berbeda          Sama         Berbeda
IAM yang berbeda          Tidak        Ya
CI/CD pipeline            Sama         Berbeda
Blast radius isolation    Rendah       Tinggi

REKOMENDASI:
- Proyek kecil, 1-2 developer → Workspace
- Proyek besar, banyak tim → Directory-based
- Compliance ketat → Directory-based
flowchart TD
    A["Pilih strategy"] --> B{"Berapa
environment?"}
    B -->|"< 4"| C{"Perbedaan
config?"}
    B -->|">= 4"| D["Directory-based ✅"]
    C -->|"Kecil"| E["Workspace ✅"]
    C -->|"Besar"| D

    style D fill:#e8f5e9,stroke:#2e7d32
    style E fill:#e3f2fd,stroke:#1565c0

Workspace Automation #

# Script untuk manage workspace
#!/bin/bash
WORKSPACE=$1

# Create workspace jika belum ada
terraform workspace select $WORKSPACE 2>/dev/null ||   terraform workspace new $WORKSPACE

# Apply dengan workspace-specific variables
terraform apply -var-file="environments/$WORKSPACE.tfvars" -auto-approve

Workspace Naming Convention #

# BEST PRACTICE: Consistent naming convention

# Format: {project}-{environment}-{component}
terraform workspace new myapp-dev-networking
terraform workspace new myapp-dev-compute
terraform workspace new myapp-staging-networking
terraform workspace new myapp-production-networking

# List semua workspace
terraform workspace list

# Select workspace
terraform workspace select myapp-production-networking

# Show current workspace
terraform workspace show

# Delete workspace (hati-hati!)
terraform workspace delete myapp-old-feature
# Gunakan workspace name di konfigurasi
locals {
  # Parse workspace name
  parts       = split("-", terraform.workspace)
  environment = element(local.parts, 1)  # dev, staging, production
  
  name_prefix = "${local.parts[0]}-${local.environment}"
}

resource "aws_instance" "web" {
  tags = {
    Name        = "${local.name_prefix}-web"
    Environment = local.environment
  }
}

Workspace vs Directory #

WORKSPACE PROS:
+ Simpler setup
+ Same code, different state
+ Quick switching

WORKSPACE CONS:
- Easy to accidentally apply wrong env
- Same code = no env-specific customization
- No code review per environment

DIRECTORY PROS:
+ Clear separation
+ Per-environment customization
+ Independent code review
+ Easy to understand

DIRECTORY CONS:
+ More files to maintain
+ Code duplication risk
+ Need shared modules

RECOMMENDATION: Gunakan directory-based
untuk production, workspace untuk dev/testing

Workspace CLI Commands #

# Workspace management commands
terraform workspace list          # List all workspaces
terraform workspace show          # Show current workspace
terraform workspace select dev    # Switch to dev workspace
terraform workspace new staging   # Create new workspace

# Use workspace in configuration
resource "aws_instance" "web" {
  instance_type = terraform.workspace == "production" ? "t3.large" : "t3.micro"
  
  tags = {
    Environment = terraform.workspace
  }
}

# Script: switch and apply
#!/bin/bash
ENV=${1:-dev}
terraform workspace select "$ENV"
terraform apply -var-file="environments/$ENV.tfvars"

Ringkasan #

  • Workspace memisahkan state, bukan konfigurasi — satu direktori .tf, banyak state file di lokasi terpisah.
  • terraform.workspace bisa digunakan dalam konfigurasi untuk perbedaan perilaku antar workspace — paling bersih dengan pola lookup map local.workspace_config[terraform.workspace].
  • Keterbatasan utama: satu backend untuk semua workspace, tidak bisa multi-account, mudah lupa workspace aktif.
  • Tepat untuk ephemeral environment (per-PR, per-feature) dan tim kecil dengan environment yang sangat mirip.
  • Tidak tepat untuk production yang butuh isolasi AWS account, akses terkontrol per-environment, atau konfigurasi yang sangat berbeda.
  • Selalu tampilkan workspace aktif di prompt shell dan tambahkan konfirmasi sebelum apply untuk mencegah kesalahan yang tidak perlu.

← Sebelumnya: Jenis Environment   Berikutnya: Directory Based →

About | Author | Content Scope | Editorial Policy | Privacy Policy | Disclaimer | Contact