You can download this code by clicking the button below.
This code is now available for download.
This function uses the boto3 library to create a randomly named S3 bucket and checks if the bucket name is already in use.
Technology Stack : boto3
Code Type : The type of code
Code Difficulty : Intermediate
import boto3
import random
def random_s3_bucket_name(prefix):
"""
Generate a random S3 bucket name with a given prefix.
"""
client = boto3.client('s3')
while True:
# Generate a random string of 10 characters
random_string = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=10))
bucket_name = f"{prefix}{random_string}"
try:
# Check if the bucket name is available
client.head_bucket(Bucket=bucket_name)
except client.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'NoSuchBucket':
break
else:
raise e
return bucket_name