skip to Main Content

I am trying to deploy a static website using an S3 bucket with Terraform.

Therefore I need to use the a aws_s3_bucket_policy resource:

resource "aws_s3_bucket_policy" "bucket" {
  bucket = aws_s3_bucket.bucket.id

  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [
      {
        Sid       = "PublicReadGetObject"
        Effect    = "Allow"
        Principal = "*"
        Action    = "s3:GetObject"
        Resource  = [
          aws_s3_bucket.bucket.arn,
          "${aws_s3_bucket.bucket.arn}/*",
        ]
      },
    ]
  })
}

When I try to deploy this I get the following error:

Error: putting S3 policy: AccessDenied: Access Denied

2

Answers


  1. since the s3 bucket exists already, the PutBucketPolicy needs to be assigned for the user or role being used:

    1. in iam: add a policy that grants the appropriate permissions for the user or role being used.
    2. s3 bucket policy: add a policy that grants the appropriate permissions for the user or role being used.

    the 2nd item isn’t needed unless the bucket policy restricts bucket policy updates.

    if you can view the bucket policy, you can see who has the appropriate permissions to update the bucket policy. if not active user or role has access to update the bucket policy, you’ll need to use the aws account root user to update the bucket policy to grant an active user the update the bucket policy.

    Login or Signup to reply.
  2. AWS has changed default permissions for newly created buckets in April this year. Since then public access is fully restricted by default, so you are not able to put your access policy without enabling proper option. You can try to use this Terraform resource, to unblock public policies:

    resource "aws_s3_bucket" "example" {
      bucket = "example"
    }
    
    resource "aws_s3_bucket_public_access_block" "example" {
      bucket = aws_s3_bucket.example.id
    
      block_public_policy     = false // This is default, so you can probably remove this line
      restrict_public_buckets = false // same as above
      block_public_acls       = true 
      ignore_public_acls      = true 
    }
    

    This will probably overwrite default bucket settings. I think that you will also need to use depends_on = [ aws_s3_bucket_public_access_block.example ] in policy resource to make sure that those options will be changed before terraform attach policy to bucket.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search