Terraform validation issue

the follow validation fails when var.saml_app.key_years_valid is null. Then I have others with the var.saml_app being null. It seems like it is erroring due to not being able to validate a null value. How can this be handled? Here is my config

validation {
  condition = (
    (var.saml_app == null || 
    var.saml_app.key_years_valid == null )|| 
    (var.saml_app.key_years_valid >= 2 && var.saml_app.key_years_valid <= 10)
  )
  error_message = "When specified, key_years_valid must be between 2 and 10 years."
}

Here is the error I get

 Error: Operation failed
│ 
│   on variables.tf line 268, in variable "saml_app":
│  268:     (var.saml_app.key_years_valid >= 2 && var.saml_app.key_years_valid <= 10)
│     ├────────────────
│     │ var.saml_app.key_years_valid is null
│ 
│ Error during operation: argument must not be null.
╵
╷
│ Error: Operation failed
│ 
│   on variables.tf line 268, in variable "saml_app":
│  268:     (var.saml_app.key_years_valid >= 2 && var.saml_app.key_years_valid <= 10)
│     ├────────────────
│     │ var.saml_app.key_years_valid is null
│ 
│ Error during operation: argument must not be null.

hi @andrew-kemp-dahlberg,

The error you are seeing is because the || operator is not short-circuiting, so even if key_years_valid is null, the entire expression must still be valid.

The next minor release of Terraform will have improved evaluation of boolean operators to short-circuit many cases, and may work around evaluation error depending on the actual example and input values.

You could alternatively write the validation using the try function:

try(var.saml_app.key_years_valid >= 2 && var.saml_app.key_years_valid <= 10, true)
2 Likes