Skip to content

Instantly share code, notes, and snippets.

@kagarlickij
Created December 16, 2019 09:05
Show Gist options
  • Save kagarlickij/21774cc939ead3af16be0c6d8da518e6 to your computer and use it in GitHub Desktop.
Save kagarlickij/21774cc939ead3af16be0c6d8da518e6 to your computer and use it in GitHub Desktop.
Snippet creates AWS S3 bucket using Python with Boto3
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.create_bucket
import json
import boto3
from botocore.exceptions import ClientError
# Default values
aws_region = 'eu-west-1'
client_name = 'kag'
environment = 'sbx'
# Module's input
aws_s3_bucket_name = 'jxes6k'
def createS3(aws_region, aws_s3_bucket_name, client_name, environment):
print('createS3 function has been started..')
session = boto3.session.Session()
client = session.client(
service_name = 's3',
region_name = aws_region
)
try:
client.create_bucket(
Bucket = aws_s3_bucket_name,
CreateBucketConfiguration = {
'LocationConstraint': aws_region
}
)
except ClientError as boto_err:
print(f'Error occurred: {boto_err}')
exit(1)
try:
client.put_bucket_encryption(
Bucket = aws_s3_bucket_name,
ServerSideEncryptionConfiguration={
'Rules': [
{
'ApplyServerSideEncryptionByDefault': {
'SSEAlgorithm': 'AES256'
}
},
]
}
)
except ClientError as boto_err:
print(f'Error occurred: {boto_err}')
exit(1)
try:
client.put_bucket_tagging(
Bucket = aws_s3_bucket_name,
Tagging={
'TagSet': [
{
'Key': 'client_name',
'Value': client_name
},
{
'Key': 'environment',
'Value': environment
}
]
}
)
except ClientError as boto_err:
print(f'Error occurred: {boto_err}')
exit(1)
else:
print('createS3 function has been completed successfully..')
# Module's output (to be used by other modules and/or UI)
aws_s3_bucket_arn = f'arn:aws:s3:::{aws_s3_bucket_name}'
return [aws_s3_bucket_arn]
s3_bucket = createS3(
aws_region = aws_region,
aws_s3_bucket_name = aws_s3_bucket_name,
client_name = client_name,
environment = environment
)[0]
print(f'DEBUG: AWS S3 bucket ARN = {s3_bucket}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment