【问题标题】:Dynamic block with optional data带有可选数据的动态块
【发布时间】:2021-06-12 09:17:56
【问题描述】:

假设我们有这个本地人:

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


    【解决方案1】:

    您可以使用第二个嵌套的 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 作为任意占位符。

    【讨论】:

    • 很酷很酷。只需将代码编辑为:for_each = schema.value.attribute_data_type
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2022-06-17
    • 2022-07-04
    • 2021-01-14
    • 2019-04-05
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多