MLu
MLu

Reputation: 1380

Build a S3 bucket policy with terraform dynamic blocks

I'm trying to create a S3 Bucket Policy to provide access to a number of other accounts. I can't figure out how to do it with Terraform either with a for loop or with dynamic blocks.

locals {
  account_ids = [
    987654321098,
    765432109876,
    432109876543
  ]
}

resource "aws_s3_bucket_policy" "bucket" {
  bucket = aws_s3_bucket.bucket.id

  policy = jsonencode({
    Statement = [
      for account in local.account_ids : {
          Effect    = "Allow"
          Action    = [ ... ]
          Principal = { AWS = [ "arn:aws:iam::${account}:root" ] }
          Resource  = "${aws_s3_bucket.bucket.arn}/states/${account}/*"
        }
      ]
    }
  })
}

This fails with: Error: Missing argument separator / A comma is required to separate each function argument from the next.

If I try a dynamic block it's a similar issue.

Ultimately I want the Statement block to contain a list of 3 blocks, one for each account.

Any ideas?

Upvotes: 2

Views: 1821

Answers (1)

Marcin
Marcin

Reputation: 238209

You have too many closing brackets. It should be:

resource "aws_s3_bucket_policy" "bucket" {
  bucket = aws_s3_bucket.bucket.id

  policy = jsonencode({
    Statement = [
      for account in local.account_ids : {
          Effect    = "Allow"
          Action    = [ ... ]
          Principal = { AWS = [ "arn:aws:iam::${account}:root" ] }
          Resource  = "${aws_s3_bucket.bucket.arn}/states/${account}/*"
        }
      ]
    })
}

Upvotes: 2

Related Questions