Terraform iterate over list

Rafael Marques picture Rafael Marques · Oct 16, 2018 · Viewed 17k times · Source

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?

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?

Answer

Magd Kudama picture Magd Kudama · Oct 16, 2018

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 = ["${locals.accounts_arn}"]
}

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