Conditional Resources in Modules
What you'll learn: How to make resources within a module optional based on input variables using count and for_each.
The Core Idea
Sometimes you want a module to create certain resources only under specific conditions. For example, a networking module might optionally create a NAT gateway, or a compute module might skip creating a load balancer if it's not needed. By combining count or for_each with input variables, you can make resource creation conditional—the module caller decides what gets built.
Using count for Conditional Logic
The count meta-argument can use a conditional expression. When count = 0, Terraform creates zero instances (effectively skipping that resource):
variable "enable_monitoring" {
type = bool
default = false
}
resource "aws_cloudwatch_dashboard" "app" {
count = var.enable_monitoring ? 1 : 0
dashboard_name = "app-dashboard"
# ... other configuration
}
If enable_monitoring is false, no dashboard is created. If true, exactly one is created.
Using for_each for Conditional Creation
You can also use for_each with an empty map or set to conditionally create resources:
variable "create_backup" {
type = bool
}
resource "aws_backup_plan" "main" {
for_each = var.create_backup ? toset(["enabled"]) : toset([])
name = "backup-plan"
# ... configuration
}
When create_backup is false, the empty set means zero instances.
Why This Matters
This pattern makes modules flexible and reusable across different environments—production might enable all features, while development skips expensive monitoring or backup resources.
Key Takeaway: Use count with ternary expressions (condition ? 1 : 0) or for_each with conditional sets to make resources within modules optional based on input variables, enabling flexible, environment-aware infrastructure.