Terrafrom v11.13内联资源循环

时间:2019-09-20 05:58:28

标签: terraform terraform-provider-aws

我希望将IAM策略附加到一部分IAM角色上,而不是全部。这在下面记录,想知道是否可以使用内联资源进行循环?在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}"
}

1 个答案:

答案 0 :(得分:0)

好的-因此,在解决此问题后,可以使用

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}"
}
相关问题