0

I have the following terraform code for creating an Azure resource group using a map(object). I was attempting to also put in some validation conditions to the variable, but it errors out saying

│ 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.

CODE

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

Can we not use validation when using map(object)?

0

1 Answer 1

1

A map(object) is enumerable/iterable and contains an arbitrary key, so you must likewise validate on the iterated values, and ignore the unknown key:

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-\"."
}
Sign up to request clarification or add additional context in comments.

1 Comment

wow, ok. I will try that out and see how it works. Thanks.

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.