S3 bucket aws_iam_policy_document

Hi Friends,

I have the following code:

variable "bucket_name" {
    type = list(string)
    description = "Name of tables to be created"
    default = [
        "demo.jagho.tk",
        "developer.jagho.tk"
        ]
}
data aws_iam_policy_document allow_public_s3_read {
    for_each = toset(var.bucket_name)

    statement {
        sid    = "PublicReadGetObject"
        effect = "Allow"
        actions = [
            "s3:GetObject",
        ]
    principals {
        type        = "AWS"
        identifiers = [ "*" ]
    }
    resources = [
        "arn:aws:s3:::${var.account_id}-${var.asset_id}-${var.env_type}-${each.value}-${var.aws_region}",
        "arn:aws:s3:::${var.account_id}-${var.asset_id}-${var.env_type}-${each.value}-${var.aws_region}/*"
    ]
  }
}
resource aws_s3_bucket bucket_names {
  for_each = toset(var.bucket_name)

  bucket  = "${var.account_id}-${var.asset_id}-${var.env_type}-${each.value}-${var.aws_region}"

  lifecycle {
    prevent_destroy = true
  }
}
resource "aws_s3_bucket_acl" "bucket_names_acl" {
  for_each  = aws_s3_bucket.bucket_names
  
  bucket    = each.value.bucket
  acl       = var.acls
}

Every thing works up until the point when I try to add the following policy to the buckets:

resource "aws_s3_bucket_policy" "s3_public_read" {
    for_each  = data.aws_iam_policy_document.allow_public_s3_read
    bucket    = each.value.id
    policy    = each.value.json
}

I get the following error:

To give a bit of context I have about 150 static websites that need to be loaded so I don’t want to have to add the policy manually on each bucket…
Any pointers will be highly appreciated…
Thanks…

What did you mean to do here?

Hi @macmiranda,

Thank you for getting back to me so quickly…

This iterates over the buckets and applies the policy to the bucket…

However I have resolved the issue was just going to post an update for anybody else who might have been faced with the same issue…

bucket    = "$
{var.account_id}-${var.asset_id}-${var.env_type}-${each.key}-${var.aws_region}"

was the issue I was using ${each.id}

bucket = each.id

and it was supposed to be:

bucket = "{var.account_id}-${var.asset_id}-${var.env_type}-${each.key}-${var.aws_region}"

This can now be closed…
Have a great day…

If that’s what you meant to do, then you should have used the same for_each you used in aws_s3_bucket_acl and referenced the policy in the aws_s3_bucket_policy resource like so:

policy    = data.aws_iam_policy_document.allow_public_s3_read.json

I doubt the changes you mentioned in your last message were the only fix.