Create a Bucket:
In your python file first import boto3 then create a low-level s3 client.
import boto3
client = boto3.client('s3')
client.create_bucket(
Bucket='my-bucket-name',
CreateBucketConfiguration={
'LocationConstraint': 'ap-east-1'
}
)
To apply a Bucket Policy:
import boto3
import json
my_bucket_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:DeleteObject",
"s3:GetObject",
"s3:PutObject"
],
"Resource": ["arn:aws:s3:::my-bucket-name/*"]
}
]
}
my_policy_string = json.dumps(my_bucket_policy)
client = boto3.client('s3')
client.put_bucket_policy(
Bucket='my-bucket-name',
Policy=my_policy_string
)
Configure Server-side Encryption on the bucket
import boto3
client = boto3.client('s3')
client.put_bucket_encryption(
Bucket='my-bucket-name',
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'AES256'
}
}
]
}
)
List Buckets
import boto3
client = boto3.client('s3')
bucket_list = client.list_buckets()
for bucket in bucket_list['Buckets']:
print(f'{bucket["Name"]}')
Delete a Bucket
import boto3
client = boto3.client('s3')
client.delete_bucket(Bucket='my-bucket-name')
Uploading files
import boto3
import os
file_name = 'sample1.txt'
file_path = os.path.dirname(__file__) + '/' + file_name
client = boto3.client('s3')
client.upload_file(file_path, 'my-bucket-name, file_name)