How to use Boto3 and AWS Client to determine whether a root bucket exists in S3?


Problem Statement − Use Boto3 library in Python to determine whether a root bucket exists in S3 or not.

Example − Bucket_1 exists or not in S3.

Approach/Algorithm to solve this problem

Step 1 − Import boto3 and botocore exceptions to handle exceptions.

Step 2 − Create an AWS session using boto3 library.

Step 3 − Create an AWS client for S3.

Step 4 − Use the function head_bucket(). It returns 200 OK if the bucket exists and the user has permission to access it. Otherwise, the response would be 403 Forbidden or 404 Not Found.

Step 5 − Handle the exception based on the response code.

Step 6 − Return True/False based on whether the bucket exists or not.

Example

The following code checks whether the root bucket exists in S3 −

import boto3
from botocore.exceptions import ClientError

# To check whether root bucket exists or not
def bucket_exists(bucket_name):
   try:
      session = boto3.session.Session()
      # User can pass customized access key, secret_key and token as well
      s3_client = session.client('s3')
      s3_client.head_bucket(Bucket=bucket_name)
      print("Bucket exists.", bucket_name)
      exists = True
   except ClientError as error:
      error_code = int(error.response['Error']['Code'])
      if error_code == 403:
         print("Private Bucket. Forbidden Access! ", bucket_name)
      elif error_code == 404:
         print("Bucket Does Not Exist!", bucket_name)
      exists = False
   return exists

print(bucket_exists('bucket_1'))
print(bucket_exists('AWS_bucket_1'))

Output

Bucket exists. bucket_1
True
Bucket Does Not Exist! AWS_bucket_1
False

Updated on: 22-Mar-2021

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements