Random S3 Bucket Name Generator with Prefix

  • Share this:

Code introduction


This function generates a random S3 bucket name based on a given prefix. The function first creates an S3 client and then generates a random suffix in a loop. It attempts to create a bucket with this name. If the bucket already exists, it catches the exception and continues generating a new random name until an unused name is found.


Technology Stack : boto3

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import boto3
import random

def generate_random_s3_bucket_name(prefix):
    """
    Generate a random S3 bucket name based on a given prefix.
    """
    client = boto3.client('s3')
    while True:
        random_suffix = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=10))
        bucket_name = f"{prefix}{random_suffix}"
        try:
            client.head_bucket(Bucket=bucket_name)
        except client.exceptions.ClientError:
            break
    return bucket_name                
              
Tags: