遍历字典列表以创建具有不同值的地形资源



目标使用地形创建两个aws_athena_named_query资源。每个查询的配置都在单独的字典中定义。所有查询字典都嵌套在一个列表中(请参见query_dict变量(。

variable query_dict {
default = [
{
name = "query1"
workgroup = "bar"
query = "SELECT * FROM foo"   
},
{
name = "query2"
workgroup = "bar"
query = "SELECT * FROM baz"   
}
]
}
resource "aws_athena_named_query" "olap" {
for_each = toset([for query in var.query_dict: {
name   = query.name
workgroup = query.workgroup
query = query.query}])
name = each.value.name
query = each.value.query
database = "test"
workgroup = each.value.workgroup
}

导致错误的原因:

The given "for_each" argument value is unsuitable: "for_each" supports maps
and sets of strings, but you have provided a set containing type object.

尝试2:

resource "aws_athena_named_query" "olap" {
for_each = [for query in tomap(var.query_dict): {
name   = query.name
workgroup = query.workgroup
query = query.query}]
name = each.value.name
query = each.value.query
database = "test"
workgroup = each.value.workgroup
} 

结果是:

Invalid value for "v" parameter: cannot convert tuple to map of any single
type.

尝试3:

resource "aws_athena_named_query" "olap" {
count = length(var.query_dict)
name = query_dict[count.index]["name"]
query = query_dict[count.index]["query"]
database = "test"
workgroup = query_dict[count.index]["workgroup"]
}

哪个输出错误:

on main.tf line 57, in resource "aws_athena_named_query" "olap":
57:   workgroup = query_dict[count.index]["workgroup"]
A reference to a resource type must be followed by at least one attribute
access, specifying the resource name.

预期输出:

# aws_athena_named_query.olap["query1"] will be created
+ resource "aws_athena_named_query" "olap" {
+ database  = "db"
+ id        = (known after apply)
+ name      = "query1"
+ query     = "SELECT * FROM foo"
+ workgroup = "bar"
}
# aws_athena_named_query.olap["query2"] will be created
+ resource "aws_athena_named_query" "olap" {
+ database  = "db"
+ id        = (known after apply)
+ name      = "query2"
+ query     = "SELECT * FROM baz"
+ workgroup = "bar"
}

我认为以下应该有效:

resource "aws_athena_named_query" "olap" {
for_each = {for idx, query in var.query_dict: idx => query}

name = each.value.name
query = each.value.query
database = "test"
workgroup = each.value.workgroup
} 

在上面,您创建了以idx为密钥的地图:

{
"0" = {
"name" = "query1"
"query" = "SELECT * FROM foo"
"workgroup" = "bar"
}
"1" = {
"name" = "query2"
"query" = "SELECT * FROM baz"
"workgroup" = "bar"
}
}

在这种情况下不需要使用for_each,因为您实际上是在迭代列表。您可以使用count:

resource "aws_athena_named_query" "olap" {
count = length(var.query_dict)
name = var.query_dict[count.index]['name']
query = var.query_dict[count.index]['query']
database = "test"
workgroup = var.query_dict[count.index]['workgroup']
}

相关内容

  • 没有找到相关文章

最新更新