Terraform - 在变量.tf 中添加 type = map(object()) 的验证

问题描述 投票:0回答:1

首先感谢这篇文章 在 variavles.tf 中添加 type = map(object()) 的默认字段,这回答了我在获取默认值以与类型 map(object() 一起使用时遇到的困难的第一部分)。我试图开始工作的最后一部分是如何验证输入值。

terraform {
  experiments = [module_variable_optional_attrs]
}

variable "dns_server" {
  description = "Add DNS Servers for domain resolution.  You can configure a maximum of two servers.  Only one can be preferred 'true'."
  type = map(object({
    preferred = optional(bool)
    server    = optional(string)
  }))
  default = {
    default = {
      preferred = false
      server    = "198.18.1.1"
    }
  }
  validation {
    condition = (
      can(regexall("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$", var.dns_server["server"]))
    )
    error_message = "The DNS Server is not a valid IPv4 Address."
  }
}

locals {
  dns_server = {
    for k, v in var.dns_server : k => {
      preferred = coalesce(v.preferred, false)
      server = coalesce(v.server, "198.18.1.1")
    }
  }
}

我知道变量字段中的默认值未使用,但我将其用作 terraform 文档输出的占位符。

我也知道上面的验证内容不正确,因为如果用户使用默认服务器 IPv4,则在本地定义之前不会进行设置。我只是不知道如何进行验证,因为我可靠的谷歌搜索没有找到任何类似的例子。

如果您需要有关如何使用它的更多详细信息,该代码位于此处:

https://github.com/scotttyso/terraform-aci-fabric/tree/main/test

如果我注释掉验证,其他一切都工作正常。预先感谢。

validation variables terraform local-variables
1个回答
15
投票

这就是你所追求的吗?

variable "mapobject" {
  type = map(object({
    cidr_block       = string
    destination_type = string
    }
  ))

  validation {
    condition     = alltrue([for o in var.mapobject : contains(["CIDR_BLOCK", "NETWORK_SECURITY_GROUP", "SERVICE_CIDR_BLOCK"], o.destination_type)])
    error_message = "All destination_types must be one of CIDR_BLOCK, NETWORK_SECURITY_GROUP or SERVICE_CIDR_BLOCK!"
  }
}

变量赋值为:

mapobject = {
  "r0" = {
    cidr_block = "10.1.1.0/24",
    destination_type = "CIDR_BLOCK"
  }
}

验证成功,但以下失败(按预期):

mapobject = {
  "r0" = {
    cidr_block = "10.1.1.0/24",
    destination_type = "**CIRD_BLOCK**"
  }
}

与先前用法相关的错误文本:

Error: Invalid value for variable
  on main.tf line 86:
  86: variable "mapobject" {

All destination_types must be one of CIDR_BLOCK, NETWORK_SECURITY_GROUP or
SERVICE_CIDR_BLOCK!

This was checked by the validation rule at main.tf:93,2-12.

如果是,那么荣誉就在这里:https://discuss.hashicorp.com/t/validate-list-object-variables/18291/2

© www.soinside.com 2019 - 2024. All rights reserved.