Manzoor Shaikh
Manzoor Shaikh

Reputation: 75

Terraform variable validation Terraform v0.13 with length & Substr

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.

Upvotes: 1

Views: 4323

Answers (1)

Marcin
Marcin

Reputation: 238687

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-\"."
  }
}

Upvotes: 1

Related Questions