【问题标题】:Terrafrom v11.13 Inline Resource LoopsTerraform v11.13 内联资源循环
【发布时间】:2020-01-21 04:03:12
【问题描述】:

我希望将 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}"
}

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

    好的 - 所以在玩了这个解决方案之后。

    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}"
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 1970-01-01
      • 2017-09-17
      • 2021-12-27
      • 2020-01-26
      • 2021-11-25
      • 2021-10-04
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多