You can download this code by clicking the button below.
This code is now available for download.
This function uses the boto3 library's S3 client to generate a random S3 bucket name that does not exist. It first generates a random suffix, then attempts to create a bucket with a combination of a given prefix and the suffix. If the bucket already exists, it will catch the exception and continue until it finds a bucket that does not exist.
Technology Stack : boto3
Code Type : The type of code
Code Difficulty : Intermediate
import boto3
import random
def generate_random_s3_bucket_name(prefix):
client = boto3.client('s3')
while True:
random_suffix = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=10))
bucket_name = f"{prefix}{random_suffix}"
try:
client.head_bucket(Bucket=bucket_name)
except client.exceptions.ClientError:
break
return bucket_name