I have 4 storage class variables that are set by default to false , then set one of them in inputs to "true" . Looking for a way to validate that only one of 4 storage classes variable is set to "true".
variable "sc1_default" {
default = "false"
}
variable "sc1_default" {
default = "false"
}
variable "sc3_default" {
default = "false"
}
variable "sc4_default" {
default = "false"
}
on terraform.tfvars Inputs
sc3_default = "true"
Option #1
We can do that with a lifecycle precondition in a null_resource
A couple of things before we dive into the code:
sc1_defaultvariables I'm assuming that the second one was a typo and what you meant there issc2_defaulttypein the variables, it's a good practice, makes the code more readable and if someone accidentally passes the wrong type the code fails gracefully.see sample code below
You can see I set the
sc3_defaultandsc4_defaultboth to true just to trigger the error ...The condition is the core of this validation we are just adding all the true with the help of shorthand if syntax
(var.sc_default ? 1 : 0)and the total should be less than two, I'm assuming that all false is OK, but if not you can change that logic to check that is precisely one.A terraform plan on that code will error out with the following message:
Option #2
If you can change the input variables we could reduce it to just one with a
list(bool)the code will be smaller and the validation would be right on the variable