Why expressions add logic in Terraform - Performance Analysis
We want to understand how adding expressions with logic affects the time it takes Terraform to process configurations.
Specifically, how does the number of logical expressions impact the work Terraform does?
Analyze the time complexity of using multiple conditional expressions in Terraform.
variable "count" {
type = number
}
resource "aws_instance" "example" {
count = var.count
ami = var.count > 5 ? "ami-abc123" : "ami-def456"
instance_type = var.count > 10 ? "t3.large" : "t3.micro"
}
This code creates multiple instances with logic deciding AMI and instance type based on the count variable.
Look at what Terraform does repeatedly when processing this code.
- Primary operation: Evaluating conditional expressions for each instance.
- How many times: Once per instance created (equal to
var.count).
As the number of instances increases, Terraform evaluates the logic for each one.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | ~10 logical evaluations |
| 100 | ~100 logical evaluations |
| 1000 | ~1000 logical evaluations |
Pattern observation: The number of logical checks grows directly with the number of instances.
Time Complexity: O(n)
This means the work grows in a straight line with the number of instances you create.
[X] Wrong: "Adding more expressions won't affect performance much because they are simple."
[OK] Correct: Even simple expressions run once per resource, so many resources mean many evaluations, increasing total work.
Understanding how logic expressions scale helps you design efficient infrastructure code that runs smoothly as it grows.
What if we replaced conditional expressions with static values? How would the time complexity change?