For each loop is not working with IAM policy resource

Hello,
I have issue with for each for iam policy. I don’t know what should I paste in, [each.key] is not working.
The problem is inside => resource “aws_iam_policy” “s3_bucket”
It is not working with [each.key] as it is shown below.

policy = data.aws_iam_policy_document.bucket_policy.*.json[each.key]

Could you help me, please?

iam.tf

# Create IAM user with policy
resource "aws_iam_user" "user" {
 for_each = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 name          = each.value.username
 force_destroy = true
}
resource "aws_iam_policy" "s3_policy" {
 for_each = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 name   = each.value.username
 description = "Allow all S3 actions"
 policy      = jsonencode({
 Version = "2012-10-17"
 Statement = [
 {
 Action = [
 "s3:*",
 ]
 Effect   = "Allow"
 Resource = [
 "${aws_s3_bucket.mybuckets[each.key].arn}",
 "${aws_s3_bucket.mybuckets[each.key].arn}/*"
 ]
 },
 ]
 })
}
resource "aws_iam_user_policy_attachment" "attach_s3_policy" {
 for_each = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 user       = each.value.username
 policy_arn = aws_iam_policy.s3_policy[each.key].arn
}
resource "aws_iam_access_key" "access_key" {
 for_each = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 user       = each.value.username
 pgp_key    = "keybase:martinsmola"
}
# S3 bucket policy
data "aws_iam_policy_document" "bucket_policy" {
 for_each = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 statement {
 actions = [
 "s3:*",
 ]
 resources = [
 "${aws_s3_bucket.mybuckets[each.key].arn}",
 "${aws_s3_bucket.mybuckets[each.key].arn}/*",
 ]
 }
}
resource "aws_iam_policy" "s3_bucket" {
 for_each    = {for bucket in var.buckets:  bucket.bucket_name => bucket}
 name        = each.value.bucket_name
 description = "Allow S3 interaction from ECS service for bucket"
 policy      = data.aws_iam_policy_document.bucket_policy.*.json
 tags        = module.generic-label.tags
}

You’ve given two different versions of your existing code at different points in the post:

I think what you’re actually looking for is

  policy = data.aws_iam_policy_document.bucket_policy[each.key].json

@maxb Hello, thank you very much for your help. I really appreciate it :slight_smile:

1 Like