Variable validation blocks in Terraform - Time & Space Complexity
When Terraform runs, it checks if variables meet rules set by validation blocks.
We want to know how the time to check variables changes as we add more variables or rules.
Analyze the time complexity of the following variable validation blocks.
variable "instance_count" {
type = number
validation {
condition = var.instance_count > 0
error_message = "Must be greater than zero."
}
}
variable "instance_names" {
type = list(string)
validation {
condition = length(var.instance_names) == var.instance_count
error_message = "Names count must match instance count."
}
}
This code checks that the number of instances is positive and that the list of names matches the count.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Evaluating each validation condition for every variable.
- How many times: Once per variable with validation blocks during plan or apply.
Each variable with validation adds a fixed number of checks.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 validation checks |
| 100 | 100 validation checks |
| 1000 | 1000 validation checks |
Pattern observation: The number of checks grows directly with the number of variables having validations.
Time Complexity: O(n)
This means the time to validate grows in a straight line as you add more variables with validation.
[X] Wrong: "Validation time stays the same no matter how many variables we add."
[OK] Correct: Each variable with validation adds extra checks, so more variables mean more time.
Understanding how validation scales helps you design Terraform code that stays fast and clear as it grows.
"What if we added nested validation inside a variable with many elements? How would the time complexity change?"