Hi everyone!
I have the following variable:
variable "backend_services" {
type = list(object({
group = string
balancing_mode = string
capacity_scaler = number
}))
default = []
}
and I’m struggling with validation for balancing_mode and capacity_scaler. Here is the validation for balancing_mode, which seems to be working fine:
validation {
condition = length([
for o in var.backend_services : true if contains(["UTILIZATION", "RATE"],
o.balancing_mode)
]) == length(var.backend_services)
error_message = "Valid values for backend_services.balancing_mode are: UTILIZATION,
RATE."
}
and here is the capacity_scaler, which is not:
validation {
condition = length([
for o in var.backend_services : o.capacity_scaler >= 0.0 && o.capacity_scaler <= 1.0
]) == length(var.backend_services)
error_message = "Valid values for backend_services.capacity_scaler are: 0.0 to 1.0 inclusive."
}
What do I miss and what should be the correct validation block for capacity_scaler?
Hi @alarinepam,
Your second example seems to be missing an if
clause, or rather it seems that you’ve written the condition for the if
as the “result”, which means that you’re producing a list of the same length as var.backend_services
but with some of the elements set to false
rather than true
and so the condition will always hold.
One way to address that would be to set the result to just true
(or any other placeholder value) and then put the condition in if
. I usually prefer to put the if
clause on a separate line to make it stand out from the main clause:
validation {
condition = length([
for o in var.backend_services : true
if o.capacity_scaler >= 0.0 && o.capacity_scaler <= 1.0
]) == length(var.backend_services)
error_message = "Valid values for backend_services.capacity_scaler are: 0.0 to 1.0 inclusive."
}
If you are using Terraform v0.14 then you can address this in a different way that might be more intuitive, using the alltrue
function which takes a list of boolean values and returns true only if all of the elements are true
:
validation {
condition = alltrue([
for o in var.backend_services : o.capacity_scaler >= 0.0 && o.capacity_scaler <= 1.0
])
error_message = "Valid values for backend_services.capacity_scaler are: 0.0 to 1.0 inclusive."
}
In this second example, we want the per-element condition to be in the result clause of the for expression, because we’re trying to produce a list of boolean values where all will be true
only if the condition holds for every element of var.backend_services
.
Thank you for the answer! Yes, it’s tf 0.13 and I’m pretty sure I tried it with
for o in var.backend_services : true
if o.capacity_scaler >= 0.0 && o.capacity_scaler <= 1.0
though let me check one more time
Looks like it’s working with true if
…
But I also checked the git history and found I used true if
already in one of the runs.
Don’t know why it didn’t not trigger error then…
Anyway, thanks for the tip, you saved my day!
We gonna need to update to 0.14