9
votes

I would like to replace the 3 indepedent variables (dev_id, prod_id, stage_id), for a single list containing all the three variables, and iterate over them, applying them to the policy.

Is this something terraform can do?

data "aws_iam_policy_document" "iam_policy_document_dynamodb" {
  statement {
    effect    = "Allow"
    resources = ["arn:aws:dynamodb:${var.region}:${var.account_id}:table:${var.dynamodb_table_name}"]

    actions = [
      "dynamodb:GetItem",
      "dynamodb:PutItem",
      "dynamodb:DeleteItem",
    ]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::${var.dev_id}:root",
        "arn:aws:iam::${var.prod_id}:root",
        "arn:aws:iam::${var.stage_id}:root"
      ]
    }
  }
}

I looked into cycles and interpolation, but It seems that 99% of the time the interpolation is done with "count" which only works for the creation of multiple resources (I hope I am not saying a big lie).

For example, I used

principals {
   count = "${length(var.list)}"
   identifiers = ["arn:aws:iam::${var.list[count.index]}"]
}

but that was unsuccessful.

Is there some way of achieving the final goal of replacing those 3 variables by a single list (or map) and iterate over them?

1
What do you want the output policy to look like? - ydaetskcoR
I want the policy to look exactly like in the first code block, that is, it should include the 3 different account ids. However, I would like to do this with iteration, and not hard-code the 3 accounts... @ydaetskcoR - Rafael Marques

1 Answers

24
votes

Given you have the list of account ids, have you tried this?

var "accounts" {
  default = ["123", "456", "789"]
  type = "list"
}

locals {
  accounts_arn = "${formatlist("arn:aws:iam::%s", var.accounts)}"
}

Then in your policy document:

principals {
  type = "AWS"
  identifiers = ["${local.accounts_arn}"]
}

I haven't actually tried it, but can't think of a reason it wouldn't work.