I really like to use CLI commands and it’s my daily routine. Today, I’ll tell to you “How do you create an S3 Bucket on AWS” and “Put an S3 Bucket Policy” via CLI. Let’s start…
The first thing, you should set your AWS_ACCESS_KEY and AWS_SECRET_ACCESS_KEY. It means you should run aws configure
the command before. If you do this, you can continue.
Check the S3 Buckets First
First of all, we need to make sure which buckets we have. When I run the aws s3 ls
command, it will return the existing buckets.
➜ ~ aws s3 ls
2021-04-26 11:01:32 ercanermis
2021-05-20 19:14:04 ercanermis-aws-ssm-logs
2021-04-26 11:01:43 ercanermis-com
2021-04-26 11:02:08 www-ercanermis-com
Create an S3 Bucket
S3 Bucket creating command is also simple and easy. It’s aws s3 mb
. Let’s do it and list buckets again.
➜ ~ aws s3 mb s3://hello-this-is-new-bucket
make_bucket: hello-this-is-new-bucket
Now, I want to list all existing buckets again to make sure.
➜ ~ aws s3 ls
2021-04-26 11:01:32 ercanermis
2021-05-20 19:14:04 ercanermis-aws-ssm-logs
2021-04-26 11:01:43 ercanermis-com
2022-07-17 14:23:29 hello-this-is-new-bucket
2021-04-26 11:02:08 www-ercanermis-com
Yes, I see my newly created bucket. The bucket name is hello-this-is-new-bucket.
Check a Bucket Policy on S3 Bucket
We created a bucket in the previous step but what about bucket policy? First of all, we need to check is there any policy existing or not. Here is an example;
➜ ~ aws s3api get-bucket-policy --bucket hello-this-is-new-bucket
An error occurred (NoSuchBucketPolicy) when calling the GetBucketPolicy operation: The bucket policy does not exist
The freshly created bucket has no policy on default. Now, time to create a policy with CLI.
Create a Bucket Policy
The policy should be in JSON format and you can create a JSON file. My bucket policy allows all users to retrieve any object hello-this-is-new-bucket
except those in the secret-folder
. It also grants put and delete permission to the “root” user of the AWS account “1234-5678-9012”.
my-s3-bucket-policy.json:
{
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::hello-this-is-new-bucket/*"
},
{
"Effect": "Deny",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::hello-this-is-new-bucket/secret-folder/*"
},
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::123456789012:root"
},
"Action": [
"s3:DeleteObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::hello-this-is-new-bucket/*"
}
]
}
Put a Bucket Policy on S3 Bucket
Putting a policy is also easy. You can see it below.
aws s3api put-bucket-policy --bucket hello-this-is-new-bucket --policy file://my-s3-bucket-policy.json
After the put-bucket-policy
command, the aws cli
doesn’t give any output but you can also know how you can check your bucket policy via CLI and you can check if you want to make sure.
Thank you so much for reading this article, happy coding!