Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create s3 bucket policy for multiple existing s3 bucket using terraform

I have some S3 buckets which are created using terraform code as below:

resource "aws_s3_bucket" "a" {
  ...
}
resource "aws_s3_bucket" "b" {
  ...
}
resource "aws_s3_bucket" "c" {
  ...
}

Now I want to create bucket policy and apply this policy for all existing s3 bucket (a, b, c). How can I get s3 bucket id and do a loop or something like that? Please advise me more. Thanks a lot!!!

resource "aws_s3_bucket_policy" "abc" {
  bucket = aws_s3_bucket.*.id
  ...
}
like image 290
Dương Quang Thọ Avatar asked Jan 22 '26 19:01

Dương Quang Thọ


1 Answers

If you create multiple buckets which just different by one or few arguments (e.g. name), you should be using count or for_each and provide the names as list. For example:

variable "buckets" {
    default = ["a", "b", "c"]
}

resource "aws_s3_bucket" "bucket" {
  for_each = var.buckets
  name     = each.key
  # ...
}

resource "aws_s3_bucket_policy" "abc" {
  for_each = var.buckets
  bucket   = aws_s3_bucket.bucket[each.key].id
  ...
}

Update

You can also do:


locals {
    buckets = [aws_s3_bucket.a, aws_s3_bucket.b, ws_s3_bucket.c]
}

resource "aws_s3_bucket_policy" "abc" {
  for_each = {for idx, bucket in local.buckets: idx => bucket}

  bucket = each.value.id
  ...
}
like image 127
Marcin Avatar answered Jan 25 '26 10:01

Marcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!