我想根据描述的项目数量创建一个策略资源。此外,这些项目之间的策略必须不同,例如,我有以下内容:
projects = ["project1", "project2"]
projects_resources = ["project1/X", "project1/Y", "project2/X", "project2/Y"]
数据来源:
data "template_file" "project_policy" {
template = file("${path.module}/project_policy.tpl")
vars = {
projects_resources = join(",", var.projects_resources)
}
}
project_policy.tpl:
...
"Resource": [
%{ for projects_resources in slice(split(",", projects_resources), 0, length(split(",", projects_resources))-1) }
"arn:aws:...${projects_resources}}",
%{ endfor }
%{ for projects_resources in slice(split(",", projects_resources), length(split(",", projects_resources))-1, length(split(",", projects_resources))) }
"arn:aws:...${projects_resources}}"
%{ endfor }
政策资源:
resource "aws_iam_policy" "iam_policies_projects" {
count = length(var.projects)
name = "policy_${var.projects[count.index]}"
policy = data.template_file.policy_projects.rendered
}
当前结果:
policy_proyect1和policy_proyect2创建:
"Resource":
"arn:aws:...proyect1/X",
"arn:aws:...proyect1/Y",
"arn:aws:...proyect2/X",
"arn:aws:...proyect2/Y"
我想要达到的目标:
policy_proyect1:
"Resource":
"arn:aws:...proyect1/X",
"arn:aws:...proyect1/Y",
policy_proyect2:
"Resource":
"arn:aws:...proyect2/X",
"arn:aws:...proyect2/Y",
我不知道是否有一种方法可以为每个策略创建2个渲染文件,其中只有与项目对应的值作为参数传递。
谢谢!
你可以创建一个新的本地地图,然后在模板中使用它:
variable "projects" {
default = ["project1", "project2"]
}
variable "projects_resources" {
default = ["project1/X", "project1/Y", "project2/X", "project2/Y", "project2/Z"]
}
locals {
proj_res_map = {for p in var.projects:
p => [for v in var.projects_resources : v if length(regexall("${p}.*", v)) > 0]
}
}
给了:
proj_res_map = {
"project1" = [
"project1/X",
"project1/Y",
]
"project2" = [
"project2/X",
"project2/Y",
"project2/Z",
]
}
然后使用它:
data "template_file" "project_policy" {
for_each = local.proj_res_map
template = file("${path.module}/project_policy.tpl")
vars = {
projects_resources = join(",", each.value)
}
}
那么iam_policies_projects
可能也需要调整,以说明template_file:
resource "aws_iam_policy" "iam_policies_projects" {
for_each = local.proj_res_map
name = "policy_${each.key}"
policy = data.template_file.policy_projects[each.key].rendered
}