Search code examples
regexvalidationvariablesterraform

Validate that a Terraform variable is a list of alphanumeric strings


I am trying to validate a variable in Terraform contains a list of alphanumeric strings. For this I'm using a regex and validating each element in the list matches this regex.

variable "list_of_strings" {
  type        = list(string)
  description = "List of alphanumeric strings (case-insensitive)"

  validation {
    condition = can(all([
      for value in var.list_of_strings : can(regex("^[A-Za-z0-9]*$", value))
    ]))
    error_message = "list_of_strings must contain only alphanumeric strings (case-insensitive)."
  }
}

Then, when I generate a plan from this MWE with the value of ["TEST"], the validation fails.

$ terraform plan -var 'list_of_strings=["TEST"]'
Planning failed. Terraform encountered an error while generating this plan.

╷
│ Error: Invalid value for variable
│
│   on variables.tf line 1:
│    1: variable "list_of_strings" {
│     ├────────────────
│     │ var.list_of_strings is list of string with 1 element
│
│ list_of_strings must contain only alphanumeric strings (case-insensitive).
│
│ This was checked by the validation rule at variables.tf:5,3-13.

I've also tried specifying the value through terraform.tfvars, but the result stays the same. What could be the issue?


Solution

  • The two issues here seem to be that your outer wrapped can(all()) function was probably intended to actually be a alltrue() function. Additionally the regexp character * was probably intended to be a + character:

    condition = alltrue([
      for value in var.list_of_strings : can(regex("^[A-Za-z0-9]+$", value))
    ])
    

    Additionally you could substitute \\w for the [A-Za-z0-9] if you want to clean it up somewhat (TF DSL requires double escapes on those characters).