Reputation: 203
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
...
}
Upvotes: 3
Views: 3146
Reputation: 238209
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
...
}
Upvotes: 4