Conditional Resource Creation
What you'll learn: How to create resources only when certain conditions are met, giving you fine-grained control over your infrastructure based on variable inputs or environment settings.
The Core Idea
Sometimes you don't want to create every resource in every situation. Maybe you only need a monitoring dashboard in production, or perhaps you want to skip creating a backup system in development environments. Conditional resource creation lets you make these decisions dynamically using Terraform's logic.
Think of it like a recipe that says "add hot sauce only if cooking for adults" — the ingredient (resource) appears or disappears based on a condition.
Three Techniques Combined
You've already learned the building blocks: count, for_each, and conditional expressions. Now you combine them:
Using Count with Ternary Operators
resource "aws_s3_bucket" "logs" {
count = var.environment == "production" ? 1 : 0
bucket = "app-logs-${var.environment}"
}
This creates the bucket only when environment is "production". Setting count = 0 means Terraform creates nothing.
Using For_Each with Conditional Logic
resource "aws_instance" "monitoring" {
for_each = var.enable_monitoring ? toset(["monitor-1"]) : toset([])
ami = var.ami_id
instance_type = "t2.micro"
}
When enable_monitoring is false, the empty set means zero instances are created.
When to Use What
Use count for simple on/off switches. Use for_each when you need more flexibility with dynamic collections or when you want cleaner state management (resources are identified by keys, not indices).
Key Takeaway: Conditional resource creation combines count/for_each meta-arguments with ternary operators to create resources only when specific conditions are true, enabling environment-specific and feature-flag-driven infrastructure.