Last active
July 18, 2021 23:09
-
-
Save andrewp-as-is/0a469634210eada3800ee0d46e2287b3 to your computer and use it in GitHub Desktop.
AWS S3 boto3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import boto3 | |
import json | |
import os | |
AWS_ACCESS_KEY_ID=os.getenv('AWS_ACCESS_KEY_ID') | |
AWS_SECRET_ACCESS_KEY=os.getenv('AWS_SECRET_ACCESS_KEY') | |
region_name=None | |
s3 = boto3.resource('s3',aws_access_key_id=AWS_ACCESS_KEY_ID,aws_secret_access_key=AWS_SECRET_ACCESS_KEY) | |
s3_client = boto3.client('s3', region_name=region_name) | |
BUCKET_NAME = 'bucket_name_xxxx121212' | |
bucket = s3.Bucket(BUCKET_NAME) | |
bucket.delete() | |
BUCKET_NAME = 'andrewp-as-is-github-io-media' | |
# list | |
response = s3_client.list_buckets() | |
# create | |
kwargs = {'Bucket':BUCKET_NAME} | |
if region_name: | |
kwargs.update({'LocationConstraint': region_name}) | |
s3_client.create_bucket(**kwargs) | |
# get | |
bucket = s3.Bucket(BUCKET_NAME) | |
if bucket.creation_date: | |
print("The bucket exists") | |
else: | |
print("The bucket does not exist") | |
# Policy | |
BUCKET_POLICY = { | |
'Version': '2012-10-17', | |
'Statement': [{ | |
'Effect': 'Allow', | |
'Principal': '*', | |
'Action': ['s3:GetObject'], | |
'Resource': "arn:aws:s3:::%s/*" % BUCKET_NAME | |
}] | |
} | |
s3_client.put_bucket_policy(Bucket=BUCKET_NAME, Policy=json.dumps(BUCKET_POLICY)) | |
policy = s3_client.get_bucket_policy(Bucket=BUCKET_NAME) | |
print(policy) | |
s3_client.delete_bucket_policy(Bucket=BUCKET_NAME) | |
# CORS | |
cors = bucket.Cors() | |
config = { | |
'CORSRules': [ | |
{ | |
'AllowedMethods': ['GET'], | |
'AllowedOrigins': ['*'] | |
} | |
] | |
} | |
cors.put(CORSConfiguration=config) | |
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/migrations3.html | |
cors.delete() | |
# delete bucket | |
bucket.delete() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment