dynamic - 带有可选数据的动态块
问题描述
假设我们有这个当地人:
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 {}
}
解决方案
您可以使用第二个嵌套块来告诉 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_each
for the nested成为一个空列表,并在我们想要生成任何块的情况下使其成为一个单元素列表来工作。dynamic
由于我们不需要对块string_attribute_constraints.key
或string_attribute_constraints.value
块内部的引用,我们可以将单个元素的值设置为任何值,因此我只需将其设置1
为任意占位符。
推荐阅读
- mysql - 将 MySQL 查询转换为 Laravel 查询构建器代码
- c++ - 使用传递引用增加另一个函数中的变量
- machine-learning - 什么时候应该训练自己的模型,什么时候应该使用预训练模型?
- typescript - 如何为 Typescript 中具有受保护成员的类编写接口
- python - 我想传递一些额外的值 Pydantics 类,这些额外的值被`@validator`方法使用
- configuration - 是否可以每次在 Python 中使用 Dispatch COMmand 打开新的 Canoe Config?
- python - 在每次迭代期间,我的列表中的所有元素都被替换而不是 1
- statistics - 将已知值外推到表中缺失值的最佳数据挖掘模型是哪个?(一般问题)
- javascript - 异步函数正在阻止 return false 工作
- azure - 缓慢批量插入 Azure 数据库