I want to create a S3 bucket with several properties:
def create_s3_bucket(name):
s3Client = boto3.client('s3')
try:
s3Client.create_bucket(
Bucket=name,
ACL="private",
CreateBucketConfiguration={
'LocationConstraint': 'eu-central-1',
},
)
except ClientError as e:
print(e)
try:
s3Client.put_public_access_block(
Bucket=name,
PublicAccessBlockConfiguration={
'BlockPublicAcls': True,
'IgnorePublicAcls': True,
'BlockPublicPolicy': True,
'RestrictPublicBuckets': True
}
)
except ClientError as e:
print(e)
try:
s3Client.put_bucket_versioning(
Bucket=name,
VersioningConfiguration={
'Status': 'Enabled'
}
)
except ClientError as e:
s3Client.put_bucket_tagging(
Bucket=name,
Tagging={
'TagSet': [
{
'Key': 'firstTag',
'Value': 'firstValue'
},
]
}
)
except ClientError as e:
print(e)
This works so far. My question is: Is there a better, more elegant way how to handle the ClientError since I keep on repeating myself in the code? If I put each API call into one try catch block, then it might be the case that one call does not event take place.
put_public_access_blockwork ifcreate_bucketfailed? You need to flesh out what the behavior of your program should be in the error cases.returnif it does not exist?