Recraftory

Deploy Infrastruktur

Best practice deploy infrastruktur dengan Terraform

Workspace Terraform

  • Mengelola environment terpisah dengan state berbeda
  • Default workspace: default
terraform workspace new staging
terraform workspace new production
terraform workspace select staging
terraform workspace list

Workflow Deploy

1. Development

terraform init
terraform plan
terraform apply

2. Code Review

  • Simpan plan output untuk review
  • terraform plan -out=tfplan
    terraform show tfplan

3. CI/CD Integration

# Contoh GitHub Actions
- name: Terraform Plan
  run: terraform plan -no-color

- name: Terraform Apply
  if: github.ref == 'refs/heads/main'
  run: terraform apply -auto-approve

Best Practice

Struktur Direktori Environment

terraform/
├── modules/
│   ├── vpc/
│   ├── ec2/
│   └── rds/
├── environments/
│   ├── dev/
│   │   ├── main.tf
│   │   └── variables.tf
│   ├── staging/
│   └── prod/

Gunakan Remote State

  • Selalu gunakan remote state untuk production
  • Aktifkan state locking
  • Enable versioning di S3 bucket state

Variabel dan Secret

  • Jangan hardcode secret
  • Gunakan environment variable atau vault
  • Gunakan sensitive = true untuk output rahasia
variable "db_password" {
  type      = string
  sensitive = true
}

Tagging

  • Tag semua resource untuk tracking biaya
  • Gunakan tag standar: Environment, Project, Owner
locals {
  common_tags = {
    Environment = var.environment
    Project     = "my-app"
    ManagedBy   = "terraform"
  }
}

Drift Detection

  • Resource dapat berubah di luar Terraform
  • Gunakan terraform plan untuk mendeteksi drift
  • Atur scheduled plan di CI/CD untuk monitoring

Destroy dengan Hati-hati

# Preview apa yang akan dihapus
terraform plan -destroy

# Gunakan target untuk destroy resource spesifik
terraform destroy -target="aws_instance.web"

Troubleshooting

  • terraform refresh: Update state dengan kondisi aktual
  • terraform taint: Mark resource untuk recreate
  • terraform untaint: Batalkan taint