Random S3 Bucket Creation using boto3

  • Share this:

Code introduction


This function uses the boto3 library to create a random S3 bucket with a name specified by the caller. The function first initializes an S3 client, then attempts to create a bucket, returning True if successful, otherwise catching an exception and returning False.


Technology Stack : boto3, S3

Code Type : Function

Code Difficulty : Intermediate


                
                    
import boto3
import random

def create_random_s3_bucket(bucket_name):
    """
    Create a random S3 bucket in the specified region.
    """
    s3 = boto3.client('s3')
    try:
        s3.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': 'us-east-1'})
        return True
    except Exception as e:
        print(f"Error creating bucket: {e}")
        return False                
              
Tags: