0

This validation block works for a single input variable.

variable "mytestname" {

     validation {
        condition = length(regexall("test$", var.mytestname)) > 0
        error_message = "Should end in test"
     }
}

I need it to work inside a for_each - or have some workaround to accomplish this. The issue is that there is a restriction on the condition statement - the condition HAS to take in the input variable itself (i.e. - it cannot accept an each.value)

variable "mytestnames" {

listnames = split(",",var.mytestnames)     

for_each = var.listnames

     validation {
        condition = length(regexall("test$", each.value)) > 0
        error_message = "Should end in test"
      }
}

The above snippet does not work. I need a way I can iterate over a list of values and validate each of them using the validation block. There must be a way to do this without a validation block...??

1

It sounds like your goal is to have a variable that takes a list and to validate each of the elements of that list. If that's true, then the approach would be to write an expression that returns true only if all of the elements are valid. For example:

variable "names" {
  type = list(string)

  validation {
    condition     = can([for v in var.names : regex("test$", v)])
    error_message = "All names must end with \"test\"."
  }
}

The above relies on the fact that regex will fail if the given string doesn't match the given pattern, and that the for expression will fail if the given expression fails for any v. can then captures the failure and returns false, making the validation fail.

3
  • Great suggestion..The trouble isn't with looping within the can statement. The issue is that you cannot pass in an element 'v' as the last argument on the condition...in other words, the validation block expects a "names" as the last argument to can[...]. That's just how hashicorp has implemented it currenlty. – user2736158 Mar 10 '20 at 21:44
  • As the person at HashiCorp who implemented this, I would expect that to work as I showed it. If not, please open an issue in Terraform's GitHub repository! 😉 – Martin Atkins Mar 11 '20 at 21:05
  • That's great to hear :) btw - I did open an issue with hashicorp (I still encounter that restriction where it expects a 'names' as the last arg in the condition). Happy coding! – user2736158 Jul 1 '20 at 2:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.