1

Terraform variable validation using length function Getting error while using length function & substr for vswitch_ids Condition - vswitch_name value must start with vsw-

variable "vswitch_ids" {
description = "The vswitch IDs."
type        = list(string)
validation {
condition = (
  length(var.vswitch_ids) > 0 &&
  substr(var.switch_ids, 0, 4) == "vsw-" 
  )
error_message = "The vswitch_name value must start with \"vsw-\"."

} }

Error: Invalid function argument 
on modules/k8s/variables.tf line 34, in variable "vswitch_ids":
34:       substr(var.vswitch_ids, 0, 4) == "vsw-" 
|----------------
| var.vswitch_ids is list of string with 3 elements
Invalid value for "str" parameter: string required.
4
  • The error is correct. var.vswitch_ids is list, not string. What do you want to achieve? Your use of substr does not make sense in your context. Commented Mar 16, 2021 at 2:02
  • what is the correct way of doing it? Commented Mar 16, 2021 at 2:04
  • Doing what? You haven't explained what do you want to do. Commented Mar 16, 2021 at 2:06
  • vswitch_name value must start with vsw- , need to do this with not using regex Commented Mar 16, 2021 at 2:13

1 Answer 1

1

The following should work. It will check if all elements in your variable list start with vsw:

variable "vswitch_ids" {
  description = "The vswitch IDs."
  type        = list(string)
  validation {
    condition = (
      length(var.vswitch_ids) > 0 &&
      length([for v in var.vswitch_ids: 1 if substr(v, 0, 4) == "vsw-"]) == length(var.vswitch_ids)
      )
      error_message = "The vswitch_name value must start with \"vsw-\"."
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.