Add a Bucket Policy to an AWS S3 Bucket

avatar

Borislav Hadzhiev

Thu Sep 23 20212 min read

banner

Photo by Ori Song

How to Add a Bucket Policy to an S3 Bucket #

Bucket policies define what actions a principal is allowed to perform on the bucket the policy is attached to.

For instance, we can define a bucket policy that allows the lambda service to perform Get* and List* actions.

To add a Bucket policy to an S3 Bucket, you have to:

  1. Open the AWS S3 console and click on your bucket's name
  2. Click on the Permissions Tab
  3. Scroll down to the Bucket Policy section and click on the Edit button

Edit bucket policy

  1. Enter a JSON bucket policy, to define which actions the principals are allowed to perform on the bucket

Let's look at an example policy, where the lambda service is granted access to perform Get* and List* actions on the bucket.

bucket-policy
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": [ "s3:Get*", "s3:List*" ], "Resource": "arn:aws:s3:::YOUR_BUCKET/*" } ] }
Note that bucket policies have a size limit of 20 KB.

In the policy above, we've allowed the lambda service to perform Get* and List* actions on all of the objects in the specified s3 bucket.

Let's look at a bucket policy which allows the users John and Bob to perform PutObject and PutObjectAcl actions on the bucket.

bucket-policy
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "arn:aws:iam::YOUR_ACCOUNT_ID:user/John", "arn:aws:iam::YOUR_ACCOUNT_ID:user/Bob", ] }, "Action": [ "s3:PutObject", "s3:PutObjectAcl" ], "Resource": "arn:aws:s3:::YOUR_BUCKET/*" } ] }

In the bucket policy example above, we've specified that the IAM users John and Bob can perform the PutObject and PutObjectAcl actions on the bucket the policy is attached to.

Let's look at another example bucket policy, which denies access to all requests initiated from IP addresses outside of a specified range.

bucket-policy
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": [ "arn:aws:s3:::YOUR_BUCKET", "arn:aws:s3:::YOUR_BUCKET/*" ], "Condition": { "NotIpAddress": {"aws:SourceIp": "12.123.123.0/24"} } } ] }

In the policy example we've denied all s3 actions on the bucket and all of its objects to all IP addresses outside of the specified range.

We've used the NotIpAddress condition to only apply the policy in cases where the requester's IP is outside of the specified range.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee