Search code examples
amazon-web-servicesterraformterraform-provider-aws

How can I assign 1 bucket policy to multiple S3 buckets using for_each in Terraform?


I'm trying to for loop and get get the interpolation correct:

variable "my_bucket_names" {
  type = list(string)
  default = [
    "b1",
    "b2",
  ]
}

resource "aws_s3_bucket_policy" "tf-thing-audit-policy" {
  for_each           = toset(var.my_bucket_names)
  bucket = ${each.key.id} 
...

Is there a way I can interpolate on the bucket value?

Error:

│ Expected the start of an expression, but found an invalid expression token.

Solution

  • each.key is of type string, not an object or a map so doing .id will result in null as it doesn't exist.

    Using the value of each.key directly will be fine for what you're trying to do (assigning 1 bucket policy to multiple buckets). You also don't need {} as you don't need to do any string interpolation for the bucket argument of aws_s3_bucket_policy.

    aws_s3_bucket_policy just requires the bucket name which is each.key:

    bucket - (Required) The name of the bucket to which to apply the policy.

    This should work perfectly fine, provided you specify a valid bucket policy:

    variable "my_bucket_names" {
      type = list(string)
      default = [
        "b1",
        "b2",
      ]
    }
    
    resource "aws_s3_bucket_policy" "tf-thing-audit-policy" {
      for_each = toset(var.my_bucket_names)
      bucket = each.key
      policy = jsonencode(...)
    }