Terraform中的嵌套循环和循环映射



我正在编写一个模块,该模块需要创建;aws_iam_group_policy_attachment"资源。此资源需要一个组名(字符串(和一个策略名称(字符串(。我尝试使用不同的数据结构,但最有意义的数据结构如下:

地图列表:

iam_groups = [
{ name = "testgroup1", policies = [ "Arn1", "Arn2" ] },
{ name = "testgroup2", policies = [ "Arn1", "Arn3", "Arn4" ] }
]

地图地图:

iam_groups = {
"testgroup1" = { name = "testgroup1", policies = ["Arn1", "Arn2" ] }
"testgroup2" = { name = "testgroup2", policies = ["Arn1", "Arn3", "Arn4" ] }
}

因为该资源不支持提供策略列表,所以我的想法是,我需要创建一个支持Group:Policy per Group的每种组合的结构,所以我定义了一个带有嵌套for循环的助手局部变量:

groups = flatten([ for group in var.iam_groups : [ for policy in group.policies : { (group.name) = policy } ] ])

这给了我正确的值组合:

+ GROUPS  = [
+ {
+ testgroup1 = "Arn1"
},
+ {
+ testgroup1 = "Arn2"
},
+ {
+ testgroup2 = "Arn1"
},
+ {
+ testgroup2 = "Arn3"
},
+ {
+ testgroup2 = "Arn4"
},
]

现在,我的问题是如何在";aws_iam_group_policy_attachment"资源

此外,是否还有其他更好的方法来构建我的数据以实现这一点?

我尝试使用:

resource "aws_iam_group_policy_attachment" "this" {
for_each = local.groups
group = each.key
policy_arn = each.value
}

但这给出了一个错误;for_each";需要一个字符串的映射或列表,其中我有一个";元组";具有多个元件。

我想避免的是维护一个变量,该变量必须手动静态地将所有组映射到每个单独的策略,并且需要大量重复。

最好将map用于for each,而不是列表,因为列表取决于项目的顺序:


locals {
groups = merge([ for group in var.iam_groups : {
for policy in group.policies :  
"${group.name}-${policy}" => { 
policy = policy 
group_name =  group.name
}
} ]...) # please do NOT remove the dots                       
}

然后

resource "aws_iam_group_policy_attachment" "this" {
for_each = local.groups
group = each.value.group_name
policy_arn = each.value.policy
}

最新更新