Variable Validation : Nested Objects

Hi,

I’m trying to see if its possible to validate nested objects. For example;

  variable "tag_templates" {
    type = list(object({
    id           = string
    display_name = optional(string)
    fields = list(object({
      id           = string
      type         = string
      values       = optional(list(string))
      description  = optional(string)
      display_name = optional(string)
      is_required  = optional(bool)
      order        = optional(number)
    }))
  }))
  description = "(Required) A list of tag template resource objects"

  validation {
    condition = can( [ for tag_template in var.tag_templates : regex("^[a-z_][a-z0-9_]{0,63}$", tag_template.id) ])
    error_message = "Each of the 'tag_templates' id values must start with a letter (a-z) or underscore (_) and only contain letters (a-z), numbers(0-9) or underscores(_)."
  }

  validation {
    condition = try( [ for field in var.tag_templates.fields : contains("STRING", field.type) ]) 
    error_message = "Supported types are 'BOOL', 'DOUBLE', 'ENUM', 'STRING' and 'TIMESTAMP'."
  }
}

Trying to make sure my nested object types attribute is one of the permitted values.
My first validation block works fine, but I’m struggling with the nested one.

Got a working solution using alltrue,

validation {
  condition = alltrue([ for tag_template in var.tag_templates : alltrue([ for field in tag_template["fields"] : contains(["BOOL", "DOUBLE", "ENUM", "STRING", "TIMESTAMP"], field["type"]) ]) ] ) 
  error_message = "Supported types are 'BOOL', 'DOUBLE', 'ENUM', 'STRING' and 'TIMESTAMP'."
}

Does seem to do what I indeeded.

1 Like