How to use Boto3 library in Python to get the list of buckets present in AWS S3?


Problem Statement − Use boto3 library in Python to get the list of all buckets present in AWS.

Example − Get the name of buckets like – BUCKET_1, BUCKET2, BUCKET_3

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 resource for S3

Step 4 − Use the function buckets.all() to list out the bucket names.

Step 5 − Handle any unwanted exception, if it occurs

Step 6 − Return the list of buckets_namev

Example

The following code gets the list of buckets present in S3 −

import boto3
from botocore.exceptions import ClientError
# To get list of buckets present in AWS using S3 resource
def get_buckets_resource():
   session = boto3.session.Session()
   # User can pass customized access key, secret_key and token as well
   s3_resource = session.resource('s3')
   try:
      buckets = list(s3_resource.buckets.all())
      print("Got buckets using resource:", buckets)
   except ClientError:
      print("Couldn't get buckets.")
      raise
   else:
      return buckets
get_buckets_resource()

Output

 
Got buckets using resource:[s3.Bucket(name='BUCKET_1'),
s3.Bucket(name='BUCKET_2'), s3.Bucket(name='BUCKET_3)………… ]


Updated on: 22-Mar-2021

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements