0

I am trying to build an IAM policy document by using a list of objects to allow multiple statements in the policy document.

s3_access = [
  {
    ext_principal_arn = "arn:aws:iam::111111111111:role/someiamrole",
    allowed_prefix    = "/home/outgoing/*",
    actions_to_allow = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:GetObjectVersion"
    ]
  },
  {
    ext_principal_arn = "arn:aws:iam::222222222222:role/someiamrole",
    allowed_prefix    = "/home/outgoing/*",
    actions_to_allow = [
      "s3:GetObject",
      "s3:GetObjectVersion"
    ]
  }
]

data "aws_iam_policy_document" "s3_cross_account_access_policy" {
  statement {
    for_each = { for access in var.s3_access : access.ext_principal_arn => access }
    principals {
      type        = "AWS"
      identifiers = [ each.value.ext_principal_arn ]
    }
    actions   = each.value.actions_to_allow
    resources = [ ${var.local_bucket_name}/each.value.allowed_prefix ]
  }
}

I am getting:

Error: each.value cannot be used in this context

We are looking to grant bucket access to different principals from different AWS accounts with detailed access control (different actions and different S3 prefixes). Would like to configure this through the input variable instead of hardcoding the policy document.

bafuwan
  • 1
  • 1

2 Answers2

1

Just try to bring the for_each instruction out of the statement block:


data "aws_iam_policy_document" "s3_cross_account_access_policy" {
  for_each = { for access in var.s3_access : access.ext_principal_arn => access }
  statement {
    principals {
      type        = "AWS"
      identifiers = [ each.value.ext_principal_arn ]
    }
    actions   = each.value.actions_to_allow
    resources = [ ${var.local_bucket_name}/each.value.allowed_prefix ]
  }
}
farhawa
  • 10,120
  • 16
  • 49
  • 91
0

Thanks @farhawa, I need for_each under the statement block. The idea is create a single policy with multiple statements for different external arns. I actually got it working with dynamic code block as the following:

data "aws_iam_policy_document" "cross_account_access_policy" {
  dynamic "statement" {
    for_each = { for access in var.s3_cors_access : access.ext_principal_arn => access }
    content {
      principals {
        type        = "AWS"
        identifiers = [statement.value.ext_principal_arn]
      }
      actions   = statement.value.actions_to_allow
      resources = ["arn:aws:s3:::${var.local_bucket_name}${statement.value.allowed_prefix}"]
    }
  }
}
bafuwan
  • 1
  • 1