EktVjRevZsTx5CccQTGFList all S3 buckets
List all S3 buckets
This task involves retrieving and displaying a comprehensive list of all Amazon S3 buckets within an AWS account. This step is crucial as it provides a clear overview of all the storage resources available, serving as a starting point for various management and security tasks, such as enforcing encryption or implementing access policies.
inputs
outputs
import boto3
from botocore.exceptions import BotoCoreError, NoCredentialsError, PartialCredentialsError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def list_all_s3_buckets():
try:
# Creating a Boto3 S3 client
s3 = boto3.client('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key)
# Sending a request to list S3 buckets
response = s3.list_buckets()
buckets_info = []
# Iterate through each bucket in the response
for bucket in response['Buckets']:
# Get the region of the bucket
location = s3.get_bucket_location(Bucket=bucket['Name'])
region = location['LocationConstraint']
if region is None:
region = 'us-east-1' # The default region if none is specified
# Append bucket details to the list
buckets_info.append({
'Name': bucket['Name'],
'Region': region
})
return buckets_info
except NoCredentialsError:
print("Error: AWS credentials not found")
return None
except PartialCredentialsError:
print("Error: Incomplete AWS credentials")
return None
except BotoCoreError as e:
print(f"Error: AWS SDK for Python (Boto3) core error occurred - {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
def display_buckets_details(buckets):
# Initialize table with the desired structure and headers
table = context.newtable()
table.title = "S3 Bucket Details"
table.num_cols = 2 # Number of columns for Name and Region
table.num_rows = 1 # Starts with one row for headers
table.has_header_row = True
# Define header names
headers = ["Bucket Name", "Region"]
# Set headers in the first row
for col_num, header in enumerate(headers):
table.setval(0, col_num, header)
# Populate the table with bucket data
for row_num, bucket in enumerate(buckets, start=1):
table.num_rows += 1 # Add a row for each bucket
values = [bucket['Name'], bucket['Region']]
for col_num, value in enumerate(values):
table.setval(row_num, col_num, value)
# Main block
buckets_info = list_all_s3_buckets()
if buckets_info is not None:
if buckets_info:
table = display_buckets_details(buckets_info)
#print("S3 bucket details are displayed in the table.")
else:
print("No S3 buckets found.")
else:
print("Error occurred while trying to list S3 buckets.")
copied