来自 v11.13 内联资源循环的地形



我希望将 IAM 策略附加到 IAM 角色的子集,而不是全部。下面对此进行了说明,并想知道是否可以使用 for 循环的内联资源?在 Terraform v11.13 中运行 AWS 提供程序。

完整列表

variable "full_list" {
description = "List of the roles to be created"
default = ["put_log_a","put_log_b","put_log_c","put_log_d","put_log_e"]
}

子列表

variable "sub_list" {
description = "Sub list of the roles"
default = ["put_log_c","put_log_e"]
}

首先创建一个 IAM 角色列表。

resource "aws_iam_role" "iam_roles" {
count                 = "${length(var.full_list)}"
name                  = "${var.role_list[count.index]}_${var.environment}"
assume_role_policy    = "${data.template_file.iam_role_trust_policy.rendered}"
force_detach_policies = "true"
tags                  = "${var.full_list_tags}"
}

然后创建 IAM 策略。

resource "aws_iam_policy" "s3_permissions_policy" {
name        = "S3_Policy_${var.environment}"
description = "S3 policy ${var.environment}"
policy      = "${file("${path.module}/files/policies/${var.environment}/s3_policy.json")}"
}

然后将策略附加到 IAM 角色的子集列表。

例-

resource "aws_iam_role_policy_attachment" "s3_policy_attachment" {
count      = "${length(var.sub_list)}"
role       = "${aws_iam_role.iam_roles.*.name[count.index]}"
policy_arn = "${aws_iam_policy.s3_permissions_policy.arn}"
}

生成错误的结果,sub_list有 2 个项目,分别位于full_list中的 2 和 4。它不是在full_list中选择正确的索引位置,而是采用full_list中的前两个索引位置。换句话说,它将策略附加到角色"put_log_a"和"put_log_b",而不是"put_log_c"和"put_log_e"。

有没有可能做这样的事情——

resource "aws_iam_role_policy_attachment" "s3_policy_attachment" {
for i "${sub_list}"
if i in "${full_list}"
then
sub_list_item_index_in_full_list = "${full_list[i]}"
role       = "${aws_iam_role.iam_roles.*.name[sub_list_item_index_in_full_list]}"
policy_arn = "${aws_iam_policy.s3_permissions_policy.arn}"
}

好的 - 所以经过一些尝试,这个解决方案有效。

resource "aws_iam_role_policy_attachment" "s3_policy_attachment" {
count      = "${length(var.sub_list)}"
role       = "${aws_iam_role.iam_roles.*.name[index(var.full_list, element(var.sub_list, count.index))]}"
policy_arn = "${aws_iam_policy.s3_permissions_policy.arn}"
}

最新更新