Terraform:字符串参数的值无效 - 变量验证语法

Terraform: Invalid value for string parameter - Variable Validation Syntax

我有以下使用地图(对象)创建 Azure 资源组的地形代码。我也试图为变量添加一些验证条件,但它出错了

│ Error: Invalid function argument
│ 
│   on variables.tf line 11, in variable "resource_groups":
│   11:     condition     = length(var.resource_groups["name"]) >= 1 && length(var.resource_groups["name"]) <= 90 && length(regexall("[^\w()-.]", var.resource_groups["name"])) == 0
│     ├────────────────
│     │ var.resource_groups["name"] is a object, known only after apply
│ 
│ Invalid value for "string" parameter: string required.
╵
╷
│ Error: Invalid function argument
│ 
│   on variables.tf line 16, in variable "resource_groups":
│   16:     condition     = substr(var.resource_groups["name"], 0, 3) == "rg-"
│     ├────────────────
│     │ var.resource_groups["name"] is a object, known only after apply
│ 
│ Invalid value for "str" parameter: string required.

代码

variable "resource_groups" {
  description = "A map of Resource groups and their properties."
  type = map(object({
    name     = string
    location = string
    tags     = map(string)
  }))

  validation {
    condition     = length(var.resource_groups["name"]) >= 1 && length(var.resource_groups["name"]) <= 90 && length(regexall("[^\w()-.]", var.resource_groups["name"])) == 0
    error_message = "The resource group name must be betweem 1 and 90 characters, using alphanumerics, underscores, parentheses, hyphens, periods."
  }

  validation {
    condition     = substr(var.resource_groups["name"], 0, 3) == "rg-"
    error_message = "The resource group name must start with \rg-\"."
  }
}

在使用map(object)的时候能不能不用validation?

A map(object) 是 enumerable/iterable 并且包含任意键,因此您必须同样验证迭代值,并忽略未知键:

validation {
  condition     = alltrue([for rg in var.resource_groups : length(rg.name) >= 1 && length(rg.name) <= 90 && length(regexall("[^\w()-.]", rg.name)) == 0])
  error_message = "The resource group name must be betweem 1 and 90 characters, using alphanumerics, underscores, parentheses, hyphens, periods."
}

validation {
  condition     = alltrue([for rg in var.resource_groups : substr(rg.name, 0, 3) == "rg-"])
  error_message = "The resource group name must start with \rg-\"."
}