Skip to content

Instantly share code, notes, and snippets.

@theskumar
Last active July 30, 2019 06:22
Show Gist options
  • Save theskumar/e349eea100f73c7f1dc5dfba324429de to your computer and use it in GitHub Desktop.
Save theskumar/e349eea100f73c7f1dc5dfba324429de to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Creates a S3 bucket and displays the access key and scret that
will have access only to the created bucket.
Setup:
$ pip install boto3
Add AWS credentials which has create bucket and IAM create permission in environment
variable or use `aws configure`
$ export AWS_ACCESS_KEY_ID=<access_key>
$ export AWS_SECRET_ACCESS_KEY=<secret_key>
python create-bucket.py
"""
import json
import re
import boto3
try:
input = raw_input
except NameError:
pass
def is_valid_bucket_name(name):
BUCKET_RE = re.compile(r'^(?![-.])(?!.*[.-]{2})[a-zA-Z0-9.-]{3,63}(?<![.-])$')
return BUCKET_RE.match(name)
iam_username = bucket_name = input("Enter S3 bucket name: ")
assert is_valid_bucket_name(bucket_name), "Please enter a valid bucket name."
iam = boto3.resource('iam')
user = iam.create_user(UserName=iam_username)
print("Created User {username} with arn={arn}".format(username=user.name,
arn=user.arn))
#
# Create AccessKey/SecretKey pair for User
#
accesskeypair = user.create_access_key_pair()
print("Access Key: %s" % accesskeypair.id)
print("Access Secret: %s" % accesskeypair.secret)
#
# Now create bucket and provide give access to user
#
s3 = boto3.resource('s3')
bucket = s3.create_bucket(Bucket=bucket_name)
bucket_policy = bucket.Policy()
s3_permissions_policy = json.dumps({
"Statement": [{
"Sid": "PublicReadForGetBucketObjects",
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": ["s3:GetObject"],
"Resource":["arn:aws:s3:::%s/*" % bucket_name]
}, {
"Action": "s3:*",
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::%s" % bucket_name,
"arn:aws:s3:::%s/*" % bucket_name
],
"Principal": {"AWS": [user.arn]}
}]
})
bucket_policy.put(Policy=s3_permissions_policy)
# Add cors configuration
cors_config = {
'CORSRules': [
{
'AllowedMethods': ['GET'],
'AllowedOrigins': ['*']
}
]
}
cors = bucket.Cors()
cors.put(CORSConfiguration=cors_config)
print("Bucket Name: %s" % bucket.name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment