首页 > 解决方案 > 带有可选数据的动态块

问题描述

假设我们有这个当地人:

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 {}
        }

标签: dynamicterraform

解决方案


您可以使用第二个嵌套块来告诉 Terraform根据您的规则生成dynamic多少块: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)
      }
    }
  }
}

这可以通过在我们不想生成任何块的情况下使for_eachfor the nested成为一个空列表,并在我们想要生成任何块的情况下使其成为一个单元素列表来工作。dynamic由于我们不需要对块string_attribute_constraints.keystring_attribute_constraints.value块内部的引用,我们可以将单个元素的值设置为任何值,因此我只需将其设置1为任意占位符。


推荐阅读