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 client for S3.
Step 4 − Use the function list_buckets() to store all the properties of buckets in a dictionary like ResponseMetadata, buckets
Step 5 − Use for loop to get only bucket-specific details from the dictionary like Name, Creation Date, etc.
Step 6 − Now, retrieve only Name from the bucket dictionary and store in a list.
Step 7 − Handle any unwanted exception if it occurs
Step 8 − Return the list of buckets_name
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 client def get_buckets_client(): session = boto3.session.Session() # User can pass customized access key, secret_key and token as well s3_client = session.client('s3') try: response = s3_client.list_buckets() buckets =[] for bucket in response['Buckets'] buckets += {bucket["Name"]} except ClientError: print("Couldn't get buckets.") raise else: return buckets print(get_buckets_client())
Output
['BUCKET_1', 'BUCKET_2', 'BUCKET_3'……..]