Terraform how to restrict s3 objects from being public

Viewed 4100

Using Terraform, I am declaring an s3 bucket and associated policy document, along with an iam_role and iam_role_policy.

The s3 bucket is creating fine in AWS however the bucket is listed as "Access: Objects can be public", and want the objects to be private. How can I explicitly make the objects private?

   resource "aws_s3_bucket" "app" {
          bucket = "${data.aws_caller_identity.current.account_id}-app"
        
          server_side_encryption_configuration {
            rule {
              apply_server_side_encryption_by_default {
                sse_algorithm     = "AES256"
              }
            }
          }
        }
    
    data "aws_iam_policy_document" "app_s3_policy" {
      statement {
        effect = "Allow"
    
        actions = [
          "s3:PutObject"
        ]
    
        resources = [
          aws_s3_bucket.app.arn,
          "${aws_s3_bucket.app.arn}/*"
        ]
      }
    }
1 Answers

The easiest way to block all objects in a bucket from ever being public is to attach an aws_s3_bucket_public_access_block resource to the bucket. It would look like this:

resource "aws_s3_bucket_public_access_block" "app" {
  bucket = aws_s3_bucket.app.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}
Related