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
- Setup: Configure development environment
- Data: Prepare required data
- Implementation: Build core functionality
- Testing: Verify correctness
- 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
countfor 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.