Generate Random AWS S3 Bucket Name with Prefix

  • Share this:

Code introduction


This function uses the boto3 library to interact with AWS S3 service to generate a random S3 bucket name with a given prefix followed by four digits. It attempts to access the bucket name, and if the bucket name does not exist (returns a 404 error), it is considered available.


Technology Stack : boto3, AWS S3

Code Type : Function

Code Difficulty : Intermediate


                
                    
import boto3
import random

def generate_random_s3_bucket_name(prefix="my-bucket-"):
    """
    Generates a random S3 bucket name using a given prefix.
    """
    client = boto3.client('s3')
    while True:
        bucket_name = f"{prefix}{random.randint(1000, 9999)}"
        try:
            client.head_bucket(Bucket=bucket_name)
            break
        except client.exceptions.ClientError as e:
            if e.response['Error']['Code'] == "404":
                break
            else:
                raise                
              
Tags: