带有可选数据的动态块

Dynamic block with optional data

假设我们有这个本地人:

locals = {
  schemas = [
    {
      name                = "is_cool"
      attribute_data_type = "Boolean"
      mutable             = true
      required            = false
    },
    {
      name                = "firstname"
      attribute_data_type = "String"
      mutable             = true
      required            = false
      min_length          = 1
      max_length          = 256
    }
  ]
}

我想实现的是使用 dynamic 构建模式,当模式是字符串时,我想添加 string_attribute_constraints 块。

这是我目前所做的,但是当架构为布尔值时它会添加一个空的 string_attribute_constraints

dynamic "schema" {
  for_each = var.schemas
  content {
    name                = schema.value.name
    attribute_data_type = schema.value.attribute_data_type
    mutable             = schema.value.mutable
    required            = schema.value.required

    string_attribute_constraints {
      min_length = lookup(schema.value, "min_length", null)
      max_length = lookup(schema.value, "max_length", null)
    }
  }
}

地形规划:

      + schema {
          + attribute_data_type = "Boolean"
          + mutable             = true
          + name                = "is_cool"
          + required            = false

          + string_attribute_constraints {}
        }

您可以使用第二个嵌套的 dynamic 块来告诉 Terraform 根据您的规则生成多少 string_attribute_constraints 块:

dynamic "schema" {
  for_each = var.schemas
  content {
    name                = schema.value.name
    attribute_data_type = schema.value.attribute_data_type
    mutable             = schema.value.mutable
    required            = schema.value.required

    dynamic "string_attribute_constraints" {
      for_each = schema.attribute_data_type == "String" ? [1] : []
      content {
        min_length = lookup(schema.value, "min_length", null)
        max_length = lookup(schema.value, "max_length", null)
      }
    }
  }
}

在我们不想生成任何块的情况下,将嵌套 dynamicfor_each 设为空列表,并将其设为单元素列表我们这样做的情况。由于我们不需要在块内引用 string_attribute_constraints.keystring_attribute_constraints.value,我们可以将单个元素的值设置为任何值,因此我只是将其设置为 1 作为任意占位符。