Optimus
Optimus

Reputation: 1825

Create multiple statements in aws_iam_policy_document with values from list of values (TF 1.13)

I have the following variable

variable "roles" {
  type = set(string)
  default = [
    "A",
    "B",
  ]
}

And I want to create a aws_iam_policy_document with a sts:AssumeRole action for each of those values.

I tried

data "aws_iam_policy_document" "service_role_trust_node_workers" {
  statement {
    effect = "Allow"
    principals {
      identifiers = ["ec2.amazon.com"]
      type = "Service"
    }
    actions = ["sts:AssumeRole"]
  }


  for_each = var.roles
  statement {
    effect = "Allow"
    sid = "${each.key}-${each.value}"
    principals {
      identifiers = [
        each.value
      ]
      type = "AWS"
    }
    actions = [
      "sts:AssumeRole"
    ]
  }
}

But this produces this

 json    = jsonencode(
            {
              + Statement = [
                  + {
                      + Action    = "sts:AssumeRole"
                      + Effect    = "Allow"
                      + Principal = {
                          + Service = "ec2.amazon.com"
                        }
                      + Sid       = ""
                    },
                  + {
                      + Action    = "sts:AssumeRole"
                      + Effect    = "Allow"
                      + Principal = {
                          + AWS = "B"
                        }
                      + Sid       = "B-B"
                    },
                ]
              + Version   = "2012-10-17"
            }
        )


So for some reason, A is ignored.

Any suggestions?

Upvotes: 2

Views: 3051

Answers (1)

Optimus
Optimus

Reputation: 1825

Ok, found it :)

dynamic "statement" {
    for_each = var.roles
    iterator = role
    content {
      effect = "Allow"
      principals {
        identifiers = [
          role.value
        ]
        type = "AWS"
      }
      actions = [
        "sts:AssumeRole"
      ]
    }
  }

Upvotes: 3

Related Questions