Create S3 Bucket with boto3 Library

  • Share this:

Code introduction


This function uses the boto3 library to create a specified S3 bucket. If the bucket name already exists or there are other errors, it will return an error message.


Technology Stack : boto3

Code Type : Function

Code Difficulty : Intermediate


                
                    
import boto3
import random

def create_random_s3_bucket(bucket_name, region_name):
    s3 = boto3.client('s3')
    try:
        s3.create_bucket(Bucket=bucket_name, CreateBucketConfiguration={'LocationConstraint': region_name})
        return f"Bucket {bucket_name} created in {region_name}"
    except Exception as e:
        return str(e)                
              
Tags: