0
resource "aws_s3_bucket" "bucket1" {
  bucket = "bucket1"
}

resource "aws_s3_bucket" "bucket2" {
  bucket = "bucket2"
}

resource "aws_s3_bucket_public_access_block" "bucket1" {
  bucket                  = aws_s3_bucket.bucket1.id
  block_public_acls       = true
  block_public_policy     = true
  restrict_public_buckets = true
  ignore_public_acls      = true
}
resource "aws_s3_bucket_public_access_block" "bucket2" {
  bucket                  = aws_s3_bucket.bucket2.id
  block_public_acls       = true
  block_public_policy     = true
  restrict_public_buckets = true
  ignore_public_acls      = true
}

I have some sample code to create two buckets (aws_s3_bucket) and and to set the public access permissions (aws_s3_bucket_public_access_block) on each bucket.

The second occurrence of the public access permissions is a duplicate of the first. Please can I have some guidance on how to simplify this into one code block and remove the duplication, such as below.

I feel like I need a loop or something, but I not quite sure what to google here.

  resource "aws_s3_bucket_public_access_block" "bucket2" {
  bucket                  = bucket1 AND bucket2
  block_public_acls       = true
  block_public_policy     = true
  restrict_public_buckets = true
  ignore_public_acls      = true
}
2
  • 1
    What you want is either for_each / count or terraform modules. Commented Jan 12, 2022 at 12:18
  • thanks, Ill take a look at them Commented Jan 12, 2022 at 12:19

1 Answer 1

2

To create multiple resources, you can use count or for_each meta-arguments. In this case refer the below code using for_each

locals {
  s3_bucket_names = {
    "bucket1" = "sample18764"
    "bucket2" = "sample2038726455"
    "bucket3" = "sample37233098"
  }
}

resource "aws_s3_bucket" "s3_storage" {
  for_each = local.s3_bucket_names

  bucket = each.value
}



resource "aws_s3_bucket_public_access_block" "block_public_access" {
  for_each = local.s3_bucket_names

  bucket                  = aws_s3_bucket.s3_storage[each.key].id
  block_public_acls       = true
  block_public_policy     = true
  restrict_public_buckets = true
  ignore_public_acls      = true
}

Sign up to request clarification or add additional context in comments.

1 Comment

If it worked, acceptance of my answer would be much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.