Search code examples
javascriptamazon-web-servicesamazon-s3aws-sdk-js

Error: "Bucket cannot have ACLs set with ObjectOwnership's BucketOwnerEnforced" on creating bucket using aws js sdk client s3


I tried to create a public-read ACL bucket using the AWS JavaScript SDK client for S3's CreateBucketCommand. It was working fine last week, but after recent AWS changes, I started receiving the following error message: 'Bucket cannot have ACLs set with ObjectOwnership's BucketOwnerEnforced'.

Here is the code I used to create the public bucket:

const command = new CreateBucketCommand({
  ACL: 'public-read',
  Bucket: bucket,
})
await this.S3Client.send(command)

What changes should I make to the code to create a public-read bucket using CreateBucketCommand that is compatible with the latest AWS changes?


Solution

  • Couldn't find a solution that can create a public bucket just by modifying CreateBucketCommand. So to achieve the result, I needed to add ObjectOwnership: 'BucketOwnerPreferred' (which is optional and the default value for ObjectOwnership is BucketOwnerPreferred ) flag to CreateBucketCommand and put public access to that bucket using PutPublicAccessBlockCommand.

    Here is the code modified to achieve the same.

      async createBucket(options) {
        const { bucket } = options
        const command = new CreateBucketCommand({
          Bucket: bucket,
          ObjectOwnership: 'BucketOwnerPreferred',
          // ACL: 'public-read',
        })
        await this.S3Client.send(command)
    
        await this.putPublicAccess(options)
    
        return { bucket }
      }
    
      async putPublicAccess(options) {
        const { bucket } = options
        const input = {
          Bucket: bucket,
          PublicAccessBlockConfiguration: {
            BlockPublicAcls: false,
            IgnorePublicAcls: false,
            BlockPublicPolicy: false,
            RestrictPublicBuckets: false,
          },
        }
        const command = new PutPublicAccessBlockCommand(input)
        await this.S3Client.send(command)
        return { bucket }
      }