Multi-Environment Management

๐Ÿ”ฅ Vibe Prompt

"Create Terraform multi-environment structure: dev/staging/prod using the same modules with different variables."

# environments/dev/main.tf
module "vpc" {
  source = "../../modules/vpc"
  vpc_cidr    = "10.0.0.0/16"
  environment = "dev"
  public_subnets  = ["10.0.1.0/24"]
  private_subnets = ["10.0.10.0/24"]
}

Deploy Commands

terraform -chdir=environments/dev init
terraform -chdir=environments/dev plan
terraform -chdir=environments/dev apply -auto-approve

Environment Strategy

| Env | Config | Cost | |-----|--------|------| | dev | Minimal | Low | | staging | Mirror prod spec | Medium | | prod | Full HA | High |

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials

Workspace Strategy

Terraform workspaces provide isolated state files for each environment.

# Workspace state files in S3
bucket: my-terraform-state
  key: env:/production/terraform.tfstate
  key: env:/staging/terraform.tfstate
  key: env:/development/terraform.tfstate

Workspace Management

# Create new workspace
export ENV=production
terraform workspace new $ENV || terraform workspace select $ENV

# Verify
echo "Current workspace: $(terraform workspace show)"

# Plan and apply
echo "Planning for $ENV..."
terraform plan -var-file="environments/$ENV.tfvars"
terraform apply -var-file="environments/$ENV.tfvars"

Directory Structure Approach

An alternative is separate directories with shared modules.

terraform/
โ”œโ”€โ”€ environments/
โ”‚   โ”œโ”€โ”€ production/
โ”‚   โ”‚   โ”œโ”€โ”€ main.tf          # References modules
โ”‚   โ”‚   โ”œโ”€โ”€ terraform.tfvars # Production values
โ”‚   โ”‚   โ””โ”€โ”€ backend.conf     # S3 backend config
โ”‚   โ”œโ”€โ”€ staging/
โ”‚   โ”‚   โ”œโ”€โ”€ main.tf
โ”‚   โ”‚   โ”œโ”€โ”€ terraform.tfvars
โ”‚   โ”‚   โ””โ”€โ”€ backend.conf
โ”‚   โ””โ”€โ”€ development/
โ”‚       โ”œโ”€โ”€ main.tf
โ”‚       โ”œโ”€โ”€ terraform.tfvars
โ”‚       โ””โ”€โ”€ backend.conf
โ”œโ”€โ”€ modules/
โ”‚   โ”œโ”€โ”€ networking/
โ”‚   โ”œโ”€โ”€ compute/
โ”‚   โ””โ”€โ”€ database/
โ””โ”€โ”€ global/
    โ”œโ”€โ”€ main.tf               # Global resources (S3 bucket, DynamoDB)
    โ””โ”€โ”€ backend.conf           # Local backend (bootstrap)

Directory Approach Commands

# Bootstrap: create S3 bucket and DynamoDB table first
cd terraform/global
terraform init
terraform apply

# Deploy development
cd terraform/environments/development
terraform init -backend-config=backend.conf
terraform apply -auto-approve

# Deploy staging
cd ../staging
terraform init -backend-config=backend.conf
terraform apply -auto-approve

# Deploy production
cd ../production
terraform init -backend-config=backend.conf
terraform apply -auto-approve

Environment Variables

| Environment | Instance Count | Instance Type | DB Size | Backup Enabled | |-------------|---------------|---------------|---------|----------------| | development | 1 | t3.micro | 10 GB | No | | staging | 2 | t3.small | 20 GB | Yes (daily) | | production | 5 | t3.medium | 100 GB | Yes (hourly) |

tfvars Files

# environments/development.tfvars
environment    = "development"
instance_count = 1
instance_type  = "t3.micro"
db_size        = 10
backup_enabled = false

# environments/production.tfvars
environment    = "production"
instance_count = 5
instance_type  = "t3.medium"
db_size        = 100
backup_enabled = true
backup_retention = 30

Conditional Logic

# Conditionally create resources based on environment
resource "aws_db_instance" "database" {
  count = var.environment == "production" ? 2 : 1  # Multi-AZ for prod
  
  allocated_storage     = var.db_size
  engine               = "postgres"
  engine_version       = "15"
  instance_class       = var.instance_type
  backup_retention_period = var.backup_enabled ? var.backup_retention : 0
  skip_final_snapshot     = var.environment == "production" ? false : true
}

# Add alerting only in production
resource "aws_cloudwatch_metric_alarm" "high_cpu" {
  count = var.environment == "production" ? 1 : 0
  
  alarm_name          = "${var.environment}-high-cpu"
  comparison_operator = "GreaterThanThreshold"
  evaluation_periods  = 2
  metric_name         = "CPUUtilization"
  namespace           = "AWS/EC2"
  threshold           = 80
}

Summary

Multi-environment management uses workspaces or separate directories. Both approaches share modules while isolating state and variables per environment.

Key takeaways:

  • Workspaces: single config, per-environment state files |
  • Directory approach: full isolation, separate backend configs |
  • tfvars files hold environment-specific values |
  • Use count for conditional resource creation |
  • Bootstrap global resources (S3, DynamoDB) separately |
  • Development = minimal, production = HA with alerting |
  • Consistent module usage across all environments |
  • Plan and review before applying to production |

You've completed this course! You now have a complete Terraform foundation.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!