Theo Sweeny
Theo Sweeny

Reputation: 1155

Terrafrom v11.13 Inline Resource Loops

I wish to attach an IAM policy to a subset of IAM roles, not all of them. This is documented below and wondering if it is possible to use an inline resource for loop? Running AWS provider, in Terraform v11.13.

Full list

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

Sub list

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

First create a list of IAM roles.

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

Then create an IAM policy.

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

Then attach the policy to a subset list of IAM roles.

Example -

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

The generates the wrong result, sub_list has 2 items, positioned at 2 and 4 in the full_list. Rather than picking their correct index positions in the full_list, it takes the first two index positions in the full_list. In other words it attaches the policy to roles "put_log_a" and "put_log_b" rather than "put_log_c" and "put_log_e.

Is it possible to do something like -

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

Upvotes: 1

Views: 392

Answers (1)

Theo Sweeny
Theo Sweeny

Reputation: 1155

Okay - so after some playing around this solution works.

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

Upvotes: 1

Related Questions