Skip to content

Instantly share code, notes, and snippets.

@Olgoetz
Last active July 31, 2020 07:06
Show Gist options
  • Save Olgoetz/29de2777c26d7202ac4c4c078faa1a5f to your computer and use it in GitHub Desktop.
Save Olgoetz/29de2777c26d7202ac4c4c078faa1a5f to your computer and use it in GitHub Desktop.
Create an AWS S3 Bucket with Boto3
def transformTags(tags):
"""Transforms the provided dictionary into a suitable array for applying within boto3.
E.g. tags ={'myTag': '1234'} will be transformed to [{'key': 'myTag, 'value:','1234'}].
Args:
tags: A dictionary with tags.
Returns:
List with [{'key': 'tagKey, 'value:','tagValue'}].
"""
tags = [{'Key': key, 'Value': value} for key, value in tags.items()]
return tags
def create_s3_bucket(bucketName, tags):
"""Create an S3 bucket. In case of any exception, delete the bucket again.
Args:
bucketName: Name of the bucket.
tags: List of tags.
Returns:
True or False depending on the API response.
Raises:
ClientError: Call to AWS API resulted in a n error.
"""
stsClient = boto3.client('sts')
s3Client = boto3.client('s3')
try:
stsResponse = stsClient.get_caller_identity()
name = f"{bucketName}-{stsResponse['Account']}"
print("Bucketname: ", name)
s3Client.create_bucket(
Bucket=name,
ACL="private",
CreateBucketConfiguration={
'LocationConstraint': 'eu-central-1',
},
)
s3Client.put_public_access_block(
Bucket=name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'IgnorePublicAcls': True,
'BlockPublicPolicy': True,
'RestrictPublicBuckets': True
}
)
s3Client.put_bucket_versioning(
Bucket=name,
VersioningConfiguration={
'Status': 'Enabled'
}
)
s3Client.put_bucket_tagging(
Bucket=name,
Tagging={
'TagSet': tags
}
)
s3Client.put_bucket_encryption(
Bucket=name,
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'aws:kms'
}
},
]
}
)
except ClientError as e:
print(e)
try:
s3Client.delete_bucket(
Bucket=name
)
except ClientError as e:
print(e)
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment