How to avoid duplicating Terraform resource code

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
}

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
}