Variable validation rules in Terraform - Time & Space Complexity
We want to understand how the time to check variable rules grows as we add more variables.
How does validation time change when we have many variables with rules?
Analyze the time complexity of the following variable validation rules.
variable "names" {
type = list(string)
validation {
condition = alltrue([for n in var.names : length(n) > 2])
error_message = "Each name must be longer than 2 characters."
}
}
variable "count" {
type = number
validation {
condition = var.count > 0
error_message = "Count must be positive."
}
}
This checks each name in a list and a single number variable for rules.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Checking each item in the list against the condition.
- How many times: Once per item in the list variable.
As the number of items in the list grows, the number of checks grows too.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows directly with the number of items.
Time Complexity: O(n)
This means the validation time grows in a straight line as the list gets bigger.
[X] Wrong: "Validation time stays the same no matter how many items are in the list."
[OK] Correct: Each item must be checked, so more items mean more checks and more time.
Understanding how validation scales helps you design efficient configurations and shows you think about cost and speed.
"What if we added nested lists inside the variable? How would the time complexity change?"